问题描述
function fibo() {
var first,second,add;
for(var i=0;i<4000;i++){
if(i === 0){
first = 1;
second = 2;
}
add = first + second;
first = second;
second = add;
}
alert(add);
}
fibo();
无法正常显示为什么无穷大?
not working shows infinity why?
推荐答案
简单:因为它太大.
第300个词是222232244629420445445529739893461909967206666939096499764990979600,所以您可以想象第4000个词有多大.您不能在JavaScript变量中保留此类值.
The 300th term is 222232244629420445529739893461909967206666939096499764990979600, so you might imagine how big the 4000th is. You can't hold such value in a JavaScript variable.
如果您真的要计算它,请使用任意精度库,如果要快速计算它,可以使用JavaScript以外的其他东西.
If you really want to calculate it, use an arbitrary precision library, and maybe something other than JavaScript if you want to calculate it fast.
检查 GNU多精度算术库-GMP .很高兴与C一起使用,它甚至具有特殊的斐波那契函数.
Check GNU Multiple Precision Arithmetic Library - GMP. Nice to use with C, and it even has special Fibonacci functions.
下面是一些C程序来完成这项工作:
Here's a little C program to do the job:
#include <gmp.h>
int main()
{
mpz_t num;
mpz_init(num);
mpz_fib_ui(num, 4000);
gmp_printf("%Zd\n", num);
return 0;
}
编译为:
cc fib.c -lgmp
然后运行:-)
time ./a.out
39909473435004422792081248094960912600792570982820257852628876326523051818641373433549136769424132442293969306537520118273879628025443235370362250955435654171592897966790864814458223141914272590897468472180370639695334449662650312874735560926298246249404168309064214351044459077749425236777660809226095151852052781352975449482565838369809183771787439660825140502824343131911711296392457138867486593923544177893735428602238212249156564631452507658603400012003685322984838488962351492632577755354452904049241294565662519417235020049873873878602731379207893212335423484873469083054556329894167262818692599815209582517277965059068235543139459375028276851221435815957374273143824422909416395375178739268544368126894240979135322176080374780998010657710775625856041594078495411724236560242597759185543824798332467919613598667003025993715274875
real 0m0.005s
user 0m0.001s
sys 0m0.002s
这篇关于为什么此斐波那契数函数返回第4000个值的无穷大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!