Fortran Implementation of Problem 2

View source code here on GitHub!

integer Problem0002/p0002()
 1! Project Euler Problem 2
 2!
 3! I modeled this after the C++ solution, because it was by far the simplest
 4!
 5! Problem:
 6!
 7! Each new term in the Fibonacci sequence is generated by adding the previous two
 8! terms. By starting with 1 and 2, the first 10 terms will be:
 9!
10! 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
11!
12! By considering the terms in the Fibonacci sequence whose values do not exceed
13! four million, find the sum of the even-valued terms.
14
15module Problem0002
16    implicit none
17contains
18    pure integer function p0002() result(answer)
19        integer :: a, b, i, tmp
20        answer = 0
21        a = 1
22        b = 2
23
24        do while (b < 4000000)
25            answer = answer + b
26
27            do i = 1, 3
28                tmp = b
29                b = a + b
30                a = tmp
31            end do
32        end do
33    end function p0002
34end module Problem0002

Tags: fibonacci-number, divisibility