您的当前位置:首页正文

和果子一起来做题-Project Euler-02-R语言版本

来源:华拓网

Project Euler01
Problem 2, 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.

400万以内的偶数斐波那契数列求和

x[1] <- 1
x[2] <- 2
for (i in 3:1000){
  x[i]=x[i-1] +f[i-2]
  if (x[i] > 4000000){
    break
  }
}
x <- x[-i]
sum(x[x %% 2 == 0])

结果4613732
但是我并不知道x[i] > 4000000时i是多少,看了别人的答案可以使用while解决这个问题

i <- 2
x <- 1:2
while (x[i] < 4e6) {
  x[i+1] <- x[i-1] + x[i]
  i <- i + 1
}
x <- x[-i]
sum(x[x %% 2 == 0])
fibonacci <- numeric()
fibonacci[1] <- 1
fibonacci[2] <- 2
i <- 3
repeat {
  fibonacci[i] <- fibonacci[i-1] + fibonacci[i-2]
  if (fibonacci[i] > 4e6) break
  i <- i + 1
}
# calculate the sum
fibonacci <- fibonacci[-length(fibonacci)]  # remove the last term
flag <- fibonacci %% 2 == 0  # find the indexes of even numbers
result <- sum(fibonacci[flag])
cat("The result is:", result, "\n")