1 ! Copyright (c) 2008 Aaron Schaefer.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.constants math.functions math.parser
4 project-euler.common sequences ;
7 ! https://projecteuler.net/problem=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
40 ! Memoized brute force
43 dup 1 > [ [ 1 - fib ] [ 2 - fib ] bi + ] when ;
47 : (digit-fib) ( n term -- term )
48 2dup fib number>string length > [ 1 + (digit-fib) ] [ nip ] if ;
50 : digit-fib ( n -- term )
55 : euler025 ( -- answer )
58 ! [ euler025 ] 10 ave-time
59 ! 5345 ms ave run time - 105.91 SD (10 trials)
65 ! A number containing 1000 digits is the same as saying it's greater than 10**999
66 ! The nth Fibonacci number is Phi**n / sqrt(5) rounded to the nearest integer
67 ! Thus we need we need "Phi**n / sqrt(5) > 10**999", and we just solve for n
71 : digit-fib* ( n -- term )
72 1 - 5 log10 2 / + phi log10 / ceiling >integer ;
76 : euler025a ( -- answer )
79 ! [ euler025a ] 100 ave-time
80 ! 0 ms ave run time - 0.17 SD (100 trials)