C memory overflow

#include <stdlib.h>
#include <stdio.h>
int main (){
   int n, cont, fib, na = 0, nb = 1, sum_even = 0;
   printf ("Insert a number and I'll tell you the respective Fibonacci: ");
   scanf ("%d", &n);
   for (cont = 1; cont < n; cont++) {
      na += nb;
      nb = na - nb;
      fib = na + nb;
      if (fib % 2 == 0) {
         sum_even += fib;
      }
   }
   printf ("%d\n", sum_even);
   return 0;
}

I tried to execute Project Euler Problem 2 , and then I came up with this code. The problem is that I can’t find the sum of the paired numbers in the Fibonacci sequence for numbers over 400 or something near them, because the memory is full. As a result, I can’t solve the exercise, as it asks me to find the sum of pair numbers below 4,000,000 in the Fibonacci sequence. Can anybody help me?

Edit: I tried using floating-point numbers to increase the response capacity, it seems to work up to a thousand or so, but if I try with large numbers, I get a -nan error in bash after 15 seconds of processing (I don't really know , what does it mean).

#include <stdlib.h>
#include <stdio.h>
int main () {
   int n, cont, div;
   float sum_even = 0, na = 0, nb = 1, fib;
   printf ("Insert a number and I'll tell you the respective Fibonacci: ");
   scanf ("%d", &n);
   for (cont = 1; cont <= n; cont++) {
      na += nb;
      nb = na - nb;
      fib = na + nb;
      div = fib / 2;
      if (div % 2 == 0) {
         sum_even += fib;
      }
   }
   printf ("%f\n", sum_even);
   return 0;
}
+3
source share
2

. ,

{ fib(n) : fib(n) <= 4000000 && fib(n) % 2 == 0 }

{ fib(n) : n <= 4000000 && fib(n) % 2 == 0 }

.

for (cont = 1; cont < n; cont++) {

while(fib <= n) {
+2

, , , . , , , . , , .

+15

All Articles