在Java中找到百万斐波那契 [英] Find The Millionth Fibonacci in Java
本文介绍了在Java中找到百万斐波那契的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在斐波那契数列中,每一项都是前两项的总和.
In Fibonacci sequence each item is the sum of the previous two.
fibonacci(1) == 1, fibonacci(0) == 0;
fibonacci(2) = fibonacci(1) + fibonacci(0);
...
在网上搜索后,我发现该算法可以解决:
After searching the web I find this algorithm to solve:
这是我的代码:
import java.math.BigInteger;
public class Fibonacci {
public static BigInteger fib(BigInteger n) {
double p = (1 + Math.sqrt(5)) / 2;
double q = (1 - Math.sqrt(5) / 2;
BigInteger result = BigInteger.ZERO;
result = ( Math.pow(p, n) - Math.pow(q, n) ) / Math.sqrt(5); //error
return result;
}
}
如何解决该错误,我希望参数为BigInteger,而不是Integer ,返回值也为BigInteger.
How to solve that error, I want the parameter is BigInteger, not Integer, and the return number is BigInteger, too.
推荐答案
您需要使用因为 Math.pow()
返回 double
,但是如果 p
和 n
太大,则会返回将引发原始溢出错误.
Because Math.pow()
returns double
, but if p
and n
are too large then it will raise primitive overflow error.
BigDecimal bp = new BigDecimal(p);
BigDecimal bq = new BigDecimal(q);
BigDecimal result = bp.pow(n); // n must be in the range 0 through 999999999, inclusive. ZERO.
现在 result
得到了 p ^ n
作为 BigDecimal
.希望您理解 BigDecimal
的计算.
Now result
got p^n
as BigDecimal
. Hope you understand the BigDecimal
calculation.
这篇关于在Java中找到百万斐波那契的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文