]> gitweb.factorcode.org Git - factor.git/blob - extra/project-euler/070/070.factor
Fix comments to be ! not #!.
[factor.git] / extra / project-euler / 070 / 070.factor
1 ! Copyright (c) 2010 Aaron Schaefer. All rights reserved.
2 ! The contents of this file are licensed under the Simplified BSD License
3 ! A copy of the license is available at http://factorcode.org/license.txt
4 USING: arrays assocs combinators.short-circuit kernel math math.combinatorics
5     math.functions math.primes math.ranges project-euler.common sequences ;
6 FROM: project-euler.common => permutations? ;
7 IN: project-euler.070
8
9 ! http://projecteuler.net/index.php?section=problems&id=70
10
11 ! DESCRIPTION
12 ! -----------
13
14 ! Euler's Totient function, φ(n) [sometimes called the phi function], is used
15 ! to determine the number of positive numbers less than or equal to n which are
16 ! relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are all less
17 ! than nine and relatively prime to nine, φ(9)=6. The number 1 is considered to
18 ! be relatively prime to every positive number, so φ(1)=1.
19
20 ! Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation
21 ! of 79180.
22
23 ! Find the value of n, 1 < n < 10^(7), for which φ(n) is a permutation of n and
24 ! the ratio n/φ(n) produces a minimum.
25
26
27 ! SOLUTION
28 ! --------
29
30 ! For n/φ(n) to be minimised, φ(n) must be as close to n as possible; that is,
31 ! we want to maximise φ(n). The minimal solution for n/φ(n) would be if n was
32 ! prime giving n/(n-1) but since n-1 never is a permutation of n it cannot be
33 ! prime.
34
35 ! The next best thing would be if n only consisted of 2 prime factors close to
36 ! (in this case) sqrt(10000000). Hence n = p1*p2 and we only need to search
37 ! through a list of known prime pairs. In addition:
38
39 !     φ(p1*p2) = p1*p2*(1-1/p1)(1-1/p2) = (p1-1)(p2-1)
40
41 ! ...so we can compute φ(n) more efficiently.
42
43 <PRIVATE
44
45 ! NOTE: ±1000 is an arbitrary range
46 : likely-prime-factors ( -- seq )
47     7 10^ sqrt >integer 1000 [ - ] [ + ] 2bi primes-between ; inline
48
49 : n-and-phi ( seq -- seq' )
50     ! ( seq  = { p1, p2 } -- seq' = { n, φ(n) } )
51     [ product ] [ [ 1 - ] map product ] bi 2array ;
52
53 : fit-requirements? ( seq -- ? )
54     first2 { [ drop 7 10^ < ] [ permutations? ] } 2&& ;
55
56 : minimum-ratio ( seq -- n )
57     [ [ first2 / ] map [ infimum ] keep index ] keep nth first ;
58
59 PRIVATE>
60
61 : euler070 ( -- answer )
62    likely-prime-factors 2 all-combinations [ n-and-phi ] map
63    [ fit-requirements? ] filter minimum-ratio ;
64
65 ! [ euler070 ] 100 ave-time
66 ! 379 ms ave run time - 1.15 SD (100 trials)
67
68 SOLUTION: euler070