Even Fibonacci numbers
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.
斐波那契数列中每一个新的项都是前两个项的和。从1和2开始,前10个项是:
1,2,3,5,8,13,21,34,55,89,...
此题重点在于斐波那契数列,教材上一般都拿这个数列来说明递归,但是设置两个中间变量可以避免递归,在实际应用中一般都会避免递归。
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.
斐波那契数列中每一个新的项都是前两个项的和。从1和2开始,前10个项是:
1,2,3,5,8,13,21,34,55,89,...
考虑斐波那契数列的项不超过400万,求所有偶数项的和。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int N;
scanf("%d", &N);
int fibona = 2, fibona_1 = 1, fibona_2 = 2, sum = 0;
while(fibona < N )
{
if(fibona % 2 == 0) sum += fibona;
fibona = fibona_1 + fibona_2;
fibona_1 = fibona_2;
fibona_2 = fibona;
}
printf("%d \n", sum);
return 0;
}
此题重点在于斐波那契数列,教材上一般都拿这个数列来说明递归,但是设置两个中间变量可以避免递归,在实际应用中一般都会避免递归。