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    integer function p0002() result(answer)
19        integer :: a
20        integer :: b
21        integer :: i
22        integer :: tmp
23        answer = 0
24        a = 1
25        b = 2
26
27        do while (b < 4000000)
28            answer = answer + b
29
30            do i = 1, 3
31                tmp = b
32                b = a + b
33                a = tmp
34            end do
35        end do
36    end function p0002
37end module Problem0002

Tags: fibonacci-number, divisibility