Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Link to original description
Source code examples on Github
Erlang version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14 # !/ usr / bin / env escript
%% -*- erlang -*-
%%! -smp enable -sname p2
% vim:syn=erlang
- mode ( compile ).
main (_) ->
Answer = lists : sum ([ X || X <- fib ([ 2 , 1 ]), X rem 2 =:= 0 ]),
io : format ( "Answer ~p ~n " ,[ Answer ]).
fib ([ H | T ]) when H >= 4000000 -> lists : reverse ( T );
fib ([ H1 , H2 | T ]) -> fib ([ H1 + H2 , H1 , H2 | T ]).
Erlang version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 # !/ usr / bin / env escript
%% -*- erlang -*-
%%! -smp enable -sname p2_1
% vim:syn=erlang
- mode ( compile ).
main (_) ->
Answer = fib ( 2 , 1 , 0 ),
io : format ( "Answer ~p ~n " ,[ Answer ]).
fib ( A , B , S ) when A >= 4000000 , B rem 2 =:= 0 -> B + S ;
fib ( A ,_, S ) when A >= 4000000 -> S ;
fib ( A , B , S ) when B rem 2 =:= 0 -> fib ( A + B , A , B + S );
fib ( A , B , S ) -> fib ( A + B , A , S ).
Perl version
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 #!/usr/bin/perl -w
use strict ;
sub main {
my @fib_array = ( 1 , 2 );
my $sum = 0 ;
while ( 1 ){
my $new_value = $fib_array [ $#fib_array ] + $fib_array [ $#fib_array - 1 ];
last if $new_value > 4000000 ;
push @fib_array , $new_value ;
}
for ( grep { ! ( $_%2 ) } @fib_array ){ $sum += $_ }
print "Answer: $sum \n"
}
main ();
Python version
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 #!/usr/bin/python
def main ():
answer = 2
fib_a = 2
fib_b = 1
while fib_a < 4000000 :
fib_a , fib_b = fib_a + fib_b , fib_a
if fib_a % 2 == 0 : answer += fib_a
print "Answer % d " % answer
main ()
Please enable JavaScript to view the comments powered by Disqus.