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 ;
7 ! http://projecteuler.net/index.php?section=problems&id=25
12 ! The Fibonacci sequence is defined by the recurrence relation:
14 ! Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1.
16 ! Hence the first 12 terms will be:
31 ! The 12th term, F12, is the first term to contain three digits.
33 ! What is the first term in the Fibonacci sequence to contain 1000 digits?
39 ! Memoized brute force
42 dup 1 > [ 1- dup fib swap 1- fib + ] when ;
46 : (digit-fib) ( n term -- term )
47 2dup fib number>string length > [ 1+ (digit-fib) ] [ nip ] if ;
49 : digit-fib ( n -- term )
54 : euler025 ( -- answer )
57 ! [ euler025 ] 10 ave-time
58 ! 5345 ms ave run time - 105.91 SD (10 trials)
64 ! A number containing 1000 digits is the same as saying it's greater than 10**999
65 ! The nth Fibonacci number is Phi**n / sqrt(5) rounded to the nearest integer
66 ! Thus we need we need "Phi**n / sqrt(5) > 10**999", and we just solve for n
70 : digit-fib* ( n -- term )
71 1- 5 log10 2 / + phi log10 / ceiling >integer ;
75 : euler025a ( -- answer )
78 ! [ euler025a ] 100 ave-time
79 ! 0 ms ave run time - 0.17 SD (100 trials)