【发布时间】:2016-06-19 17:36:46
【问题描述】:
我有以下代码,它为 n
public static int fib(int n) {
int nthTerm = 0;
if (n == 2)
nthTerm = 1;
else {
double goldenRatio = (1 + Math.sqrt(5)) / 2;
nthTerm = (int) (Math.round(Math.pow(goldenRatio, n)
- Math.pow(1 - goldenRatio, n)) / Math.sqrt(5));
if (n % 2 == 1 && n < 45)
nthTerm++;
}
return nthTerm;
}
n > 46 的任何值都超出了 int 范围。我怎样才能使这种方法适用于 n > 46?
附:我知道 BigInteger,但不是很擅长,所以我也很欣赏使用 BigInteger 的示例。
【问题讨论】:
-
使用
long代替int。 -
或
BigInteger以支持long范围之外的值。