#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 was trying to do the Project Euler Problem 2, and then I came up with this code. The problem is: I can’t find the sum of the pair numbers on fibonacci’s sequence for numbers over 400 or something near that, because memory overflows. In consequence, I cant solve the exercise, since it asks to find the sum of the pair numbers below 4000000 in fibonacci’s sequence. Can anyone help me?
Edit:
I tried to used float type numbers to increase the answer’s capacity, it seems to work till a thousand or so, but if I try with bigger numbers, I get a -nan error in bash after like 15 secs of processing (I don’t really know what it means).
#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;
}
You misunderstood the problem statement. The task is to find the sum of
and not
That task is solved without problems with a minor modification to your code. Instead of
use