/extra/project-euler/069/069.factor

http://github.com/abeaumont/factor · Factor · 84 lines · 24 code · 24 blank · 36 comment · 3 complexity · 4d57b2261e6032fead4b9b40c02e0a35 MD5 · raw file

  1. ! Copyright (c) 2009 Aaron Schaefer.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: combinators fry kernel math math.primes math.primes.factors math.ranges
  4. project-euler.common sequences ;
  5. IN: project-euler.069
  6. ! http://projecteuler.net/index.php?section=problems&id=69
  7. ! DESCRIPTION
  8. ! -----------
  9. ! Euler's Totient function, φ(n) [sometimes called the phi function], is used
  10. ! to determine the number of numbers less than n which are relatively prime to
  11. ! n. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and
  12. ! relatively prime to nine, φ(9)=6.
  13. ! +----+------------------+------+-----------+
  14. ! | n | Relatively Prime | φ(n) | n / φ(n) |
  15. ! +----+------------------+------+-----------+
  16. ! | 2 | 1 | 1 | 2 |
  17. ! | 3 | 1,2 | 2 | 1.5 |
  18. ! | 4 | 1,3 | 2 | 2 |
  19. ! | 5 | 1,2,3,4 | 4 | 1.25 |
  20. ! | 6 | 1,5 | 2 | 3 |
  21. ! | 7 | 1,2,3,4,5,6 | 6 | 1.1666... |
  22. ! | 8 | 1,3,5,7 | 4 | 2 |
  23. ! | 9 | 1,2,4,5,7,8 | 6 | 1.5 |
  24. ! | 10 | 1,3,7,9 | 4 | 2.5 |
  25. ! +----+------------------+------+-----------+
  26. ! It can be seen that n = 6 produces a maximum n / φ(n) for n 10.
  27. ! Find the value of n 1,000,000 for which n / φ(n) is a maximum.
  28. ! SOLUTION
  29. ! --------
  30. ! Brute force
  31. <PRIVATE
  32. : totient-ratio ( n -- m )
  33. dup totient / ;
  34. PRIVATE>
  35. : euler069 ( -- answer )
  36. 2 1000000 [a,b] [ totient-ratio ] map
  37. [ supremum ] keep index 2 + ;
  38. ! [ euler069 ] 10 ave-time
  39. ! 25210 ms ave run time - 115.37 SD (10 trials)
  40. ! ALTERNATE SOLUTIONS
  41. ! -------------------
  42. ! In order to obtain maximum n / φ(n), φ(n) needs to be low and n needs to be
  43. ! high. Hence we need a number that has the most factors. A number with the
  44. ! most unique factors would have fewer relatively prime.
  45. <PRIVATE
  46. : primorial ( n -- m )
  47. {
  48. { [ dup 0 = ] [ drop V{ 1 } ] }
  49. { [ dup 1 = ] [ drop V{ 2 } ] }
  50. [ nth-prime primes-upto ]
  51. } cond product ;
  52. : primorial-upto ( limit -- m )
  53. 1 swap '[ dup primorial _ <= ] [ 1 + dup primorial ] produce
  54. nip penultimate ;
  55. PRIVATE>
  56. : euler069a ( -- answer )
  57. 1000000 primorial-upto ;
  58. ! [ euler069a ] 100 ave-time
  59. ! 0 ms ave run time - 0.01 SD (100 trials)
  60. SOLUTION: euler069a