Problem 2

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,
...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
n <- 4000000
 
fibonacci <- c(1,2)
i <- 3
sum <- 2
f <- 0
while ( f < n) {
    f <- fibonacci[i-1] + fibonacci[i-2]
    fibonacci <- c(fibonacci,f)
    if (! f %% 2)
        sum = sum+f
    i = i + 1
}
 
cat ("The sum of all the even-valued terms in the
Fibonacci sequence which do not exceed four million is ", sum, "\n")

Answer:4613732

p5rn7vb

Related Posts

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>