/extra/project-euler/025/025.factor

http://github.com/abeaumont/factor · Factor · 81 lines · 20 code · 27 blank · 34 comment · 2 complexity · dfef9fcbfbedd72d64b261ecc0cdc7b2 MD5 · raw file

  1. ! Copyright (c) 2008 Aaron Schaefer.
  2. ! See http://factorcode.org/license.txt for BSD license.
  3. USING: kernel math math.constants math.functions math.parser memoize
  4. project-euler.common sequences ;
  5. IN: project-euler.025
  6. ! http://projecteuler.net/index.php?section=problems&id=25
  7. ! DESCRIPTION
  8. ! -----------
  9. ! The Fibonacci sequence is defined by the recurrence relation:
  10. ! Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
  11. ! Hence the first 12 terms will be:
  12. ! F1 = 1
  13. ! F2 = 1
  14. ! F3 = 2
  15. ! F4 = 3
  16. ! F5 = 5
  17. ! F6 = 8
  18. ! F7 = 13
  19. ! F8 = 21
  20. ! F9 = 34
  21. ! F10 = 55
  22. ! F11 = 89
  23. ! F12 = 144
  24. ! The 12th term, F12, is the first term to contain three digits.
  25. ! What is the first term in the Fibonacci sequence to contain 1000 digits?
  26. ! SOLUTION
  27. ! --------
  28. ! Memoized brute force
  29. MEMO: fib ( m -- n )
  30. dup 1 > [ [ 1 - fib ] [ 2 - fib ] bi + ] when ;
  31. <PRIVATE
  32. : (digit-fib) ( n term -- term )
  33. 2dup fib number>string length > [ 1 + (digit-fib) ] [ nip ] if ;
  34. : digit-fib ( n -- term )
  35. 1 (digit-fib) ;
  36. PRIVATE>
  37. : euler025 ( -- answer )
  38. 1000 digit-fib ;
  39. ! [ euler025 ] 10 ave-time
  40. ! 5345 ms ave run time - 105.91 SD (10 trials)
  41. ! ALTERNATE SOLUTIONS
  42. ! -------------------
  43. ! A number containing 1000 digits is the same as saying it's greater than 10**999
  44. ! The nth Fibonacci number is Phi**n / sqrt(5) rounded to the nearest integer
  45. ! Thus we need we need "Phi**n / sqrt(5) > 10**999", and we just solve for n
  46. <PRIVATE
  47. : digit-fib* ( n -- term )
  48. 1 - 5 log10 2 / + phi log10 / ceiling >integer ;
  49. PRIVATE>
  50. : euler025a ( -- answer )
  51. 1000 digit-fib* ;
  52. ! [ euler025a ] 100 ave-time
  53. ! 0 ms ave run time - 0.17 SD (100 trials)
  54. SOLUTION: euler025a