views:

144

answers:

5

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;
}
+1  A: 

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;
} 
Vladimir
+3  A: 

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, 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)

caf
why (x+y)<=4000000 and not num<=4000000?
fahad
and why start from x=1 and y=1?IF the question says the series is 1,2,3,5...
fahad
@fahad: Because the test is run *before* the loop executed, so it happens before `num` is calculated. And if you start with `x=1,y=1` then the first number tested is 3, not 2.
caf
fahad
@fahad: There lots of ways to go about it, but I was going for the minimal changes to your code.
caf
A: 

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 ) {
ArunSaha
Hmm.. Any reason for down vote? If the answer is incorrect, please comment, so that I can learn my mistake.
ArunSaha
A: 

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;
}
DigitalRoss
A: 

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;
 }
pmg