Find the sum of all even-numbered members in a sequence not exceeding four million

Each new member of the Fibonacci sequence is generated by adding the two previous members. Starting from 1 and 2, the first 10 members will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... I made a program, but my answer does not 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;
}
+3
source share
5 answers

Three problems that I see:

  • You should start with x = 1, y = 1, otherwise you will miss the first even-valued Fibonacci;
  • Your loop condition should be (x + y) <= 4000000
  • Testing numfor parity, not i.

( , i , , for while)

+3

, + 4000000 , <= 4000000. -

while ( y < 4000000){
...
if (y %2 == 0)
    sum += y;
} 
+1

. , ( , , ), , ...

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

,

if(i%2==0)

if( num % 2 == 0)

, i. :

enum { LIMIT = 4 * 1000 * 1000 };
num = x + y;
while( num <= LIMIT ) {
-1

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

Source: https://habr.com/ru/post/1767700/


All Articles