Find the sum of all the even-valued terms in the sequence which do not exceed four million
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, ... I made the program but my answer doesnt match.
#include<stdio.h>
int main()
{
long unsigned int i,sum=0,x=1,y=2开发者_运维技巧,num;
for(i=0;i<4000000;i++)
{
num=x+y;
if(i%2==0)
sum+=num;
x=y;
y=num;
}
printf("%lu\n",sum);
getchar();
return 0;
}
Three problems I can see:
- You should start with
x = 1, y = 1
, since otherwise you skip the first even-valued Fibonacci; - Your loop condition should be
(x + y) <= 4000000
- You should test
num
for even-ness, noti
.
(After these changes, it should be obvious that you can omit i
entirely, and therefore replace the for
loop with a while
loop)
In your code you find the sum of fibonacci numbers with even index, not even numbers themselves + you search the first 4000000 numbers in sequence, not the numbers with values <= 4000000. Your code should be something like
while ( y < 4000000){
...
if (y %2 == 0)
sum += y;
}
I've made a minimal set of corrections and now get the right answer. You may learn more by reading this (after all, it was yours, to start with) than by me rambling on about it...
#include <stdio.h>
#define LIMIT (4 * 1000 * 1000)
int main() {
long unsigned int sum = 0, x = 1, y = 2, num;
while (x <= LIMIT) {
if ((x & 1) == 0 && x <= LIMIT)
sum += x;
num = x + y;
x = y;
y = num;
}
printf("%lu\n", sum);
return 0;
}
I think the following line
if(i%2==0)
might instead be
if( num % 2 == 0)
On further thinking, I think you don't actually need the variable i
. Instead, your loop can be controlled by num as:
enum { LIMIT = 4 * 1000 * 1000 };
num = x + y;
while( num <= LIMIT ) {
print num inside the loop, for debugging
for(i=0;i<4000000;i++)
{
num=x+y;
printf("num is %lu\n", num); /* DEBUGGING */
if(i%2==0)
sum+=num;
x=y;
y=num;
}
精彩评论