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