Problem
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.
- #include <stdio.h>
-
-
#define NUM 4000000
-
int main(int argc, const char *argv[])
-
{
-
int fibonacci, prev, pprev;
-
int sum;
-
-
pprev = 1, prev = 2, fibonacci = 0;
-
sum = 2;
-
while (fibonacci< NUM) {
-
if (!(fibonacci % 2)) {
-
sum += fibonacci;
-
}
-
fibonacci = prev + pprev;
-
pprev = prev;
-
prev = fibonacci;
-
printf("fibonacci: %d\n", fibonacci);
-
}
-
-
printf("sum = %d\n", sum);
-
-
return 0;
-
}
阅读(1231) | 评论(0) | 转发(0) |