[英]It's about problem 8 in project euler , i can't tell why the code doesn't give me the correct answer
[英]Why doesn't this code work for a[100] and above? (project euler 2 in C)
这是我的代码:
我不明白为什么它给我50以上的错误答案。
#include<stdio.h>
int main()
{
long long int i, sum=0;
long long int a[50];
a[0] = 1;
a[1] = 1;
for(i=2;i<50;i++)
{
a[i] = a[i-1] + a[i-2];
if(a[i]%2==0 && a[i]<4000000)
sum = sum + a[i];
}
printf("%lld", sum);
return 0;
}
您有整数溢出。 斐波那契数变得非常大。 在F(94)
事情超出了64位整数的范围(例如long long
)。
F(90) = 2880067194370816120 >= 2^61
F(91) = 4660046610375530309 >= 2^62
F(92) = 7540113804746346429 >= 2^62
F(93) = 12200160415121876738 >= 2^63
F(94) = 19740274219868223167 >= 2^64
F(95) = 31940434634990099905 >= 2^64
F(96) = 51680708854858323072 >= 2^65
当溢出发生时,你会变得越来越小,甚至是负数a
而不是真正的斐波那契数的。 您需要解决此溢出问题。
当期限超过4,000,000时,您的第一个错误不是打破循环。 您无需考虑上述问题之外的其他术语; 如果您停在那里,则无需处理整数溢出; 而且您不需要50个字词就能达到目标。
同样,您也不需要存储所有术语,除非您想要查看它们以检查正确性(并且只需打印它们就可以了)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.