#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;
}
我试图做 Project Euler Problem 2,然后我想出了这段代码。问题是:我在斐波那契数列上找不到超过 400 或接近数字的数字对的总和,因为内存溢出。结果,我无法解决这个练习,因为它要求在斐波那契数列中找到低于 4000000 的对数之和。谁能帮我?
编辑:我尝试使用浮点类型数字来增加答案的容量,它似乎可以工作到一千左右,但是如果我尝试使用更大的数字,我会在 bash 处理 15 秒后出现 -nan 错误(我没有'不知道这意味着什么)。
#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;
}