Javascript斐波那契
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个术语是222232244629420445529739893461909967206666939096499764990979600,所以你可以想象第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