Reputation:
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;
}
Upvotes: 3
Views: 2329
Reputation: 108978
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;
}
Upvotes: -1
Reputation: 146043
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;
}
Upvotes: 0
Reputation: 239041
Three problems I can see:
x = 1, y = 1
, since otherwise you skip the first even-valued Fibonacci;(x + y) <= 4000000
num
for even-ness, not i
.(After these changes, it should be obvious that you can omit i
entirely, and therefore replace the for
loop with a while
loop)
Upvotes: 3
Reputation: 20383
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 ) {
Upvotes: -1
Reputation: 170839
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;
}
Upvotes: 1