Friday 16 September 2011

Project Euler: 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, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.



# Inititae a vector x with two values 1 and 2, the starting points for the Fibonacci series 
x <- c(1,2)
length(x)


# Take an object "i", with a starting value of 1. 
# This object will be used to as an index for the vector "x". 
# We continue to add# the (n - 1)th term  and the (n - 2)th term
# to get the nth term. 
# This process continues as long as an element of vector x with 
# index value "i" just crosses the 4,000,000 mark.
i <- 1
while (x[i] < 4000000){i <- i + 1
                        x.index <- length(x)
                        x[x.index + 1] <- x[x.index] + x[x.index - 1]}
x

# Sum the even values of the Fibonacci series thus obtained
sum(x[x %% 2 == 0])


Answer : 4613732

1 comment:

  1. I think it needs some correction:
    i <- 2
    while { .....
    }
    # removing the last term as it exceeds 4 million
    x <- x[1:length(x)-1]
    sum(x[x %% 2 == 0])

    # Anyways keep up the good work

    ReplyDelete