Project Euler Problem 25

1000-digit Fibonacci number.

The Fibonacci sequence is defined by the recurrence relation:
F(n) = F(n−1) + F(n−2), where F(1) = 1 and F(2) = 1.

Hence the first 12 terms will be:

F(1) = 1
F(2) = 1
F(3) = 2
F(4) = 3
F(5) = 5
F(6) = 8
F(7) = 13
F(8) = 21
F(9) = 34
F(10) = 55
F(11) = 89
F(12) = 144

The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?

Link to original description
Source code examples on Github

burtforce solution:

Erlang version 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname p25
% vim:syn=erlang

-mode(compile).


main(_) ->
    io:format("Answer: ~p ~n", [test25()]).

test25()     -> fib(1,2,2).
fib(A,B,N)   ->
    case length(integer_to_list(A)) of
        1000 -> N;
        _    -> fib(B, A+B,N+1)
    end.

after that i found this Golden Ratio and this: Fibonacci number. So more effective solution:

Erlang version 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname p25
% vim:syn=erlang

-mode(compile).


main(_) ->
    io:format("Answer: ~p ~n", [test25()]).

test25() -> 
    Phi    = (math:sqrt(5) + 1) / 2,
    C      = math:log10(5) / 2,
    LogPhi = math:log10(Phi),
    t25i(1, C, LogPhi).

t25i(N, C, L) when N * L - C >= 999 -> N;
t25i(N, C, L) -> t25i(N+1, C, L).

Python version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python3
import math

phi = (1 + pow(5, 0.5)) / 2
c = math.log10(5) / 2
logphi = math.log10(phi)
n = 1
while True:
    if n * logphi - c >= 999:
        break
    n = n + 1

print("Answer %s " % n)