Find the sum of all the even-valued terms in the sequence which do not exceed four million

安稳与你 提交于 2019-12-10 19:13:37

问题


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:


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)




回答2:


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



回答3:


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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/3847992/find-the-sum-of-all-the-even-valued-terms-in-the-sequence-which-do-not-exceed-fo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!