问题描述
我正在尝试将fibonacci系列打印到N个数字。所有的工作按照期望直到f(92)但是当我试图得到f(93)的值时,值结果为负: - 6246583658587674878。这怎么可能?下面逻辑中的错误是什么?
I am trying to printout fibonacci series upto 'N' numbers. All works as per expectation till f(92) but when I am trying to get the value of f(93), values turns out in negative: "-6246583658587674878". How this could be possible? What is the mistake in the logic below?
public long fibo(int x){
long[] arr = new long[x+1];
arr[0]=0;
arr[1]=1;
for (int i=2; i<=x; i++){
arr[i]=arr[i-2]+arr[i-1];
}
return arr[x];
}
f(91) = 4660046610375530309
f(92) = 7540113804746346429
f(93) = -6246583658587674878
这是因为数据类型吗?我应该用什么数据类型将fibonacci系列打印到N个数字? N可以是[0..10,000,000]范围内的任何整数。
Is this because of data type? What else data type I should use for printing fibonacci series upto N numbers? N could be any integer within range [0..10,000,000].
推荐答案
您遇到了:
4660046610375530309 <-- term 91
+7540113804746346429 <-- term 92
====================
12200160415121876738 <-- term 93: the sum of the previous two terms
9223372036854775808 <-- maximum value a long can store
为避免这种情况,请使用,它可以处理任意数量的数字。
这是你的实现转换为使用 BigDecimal
:
To avoid this, use BigInteger
, which can deal with an arbitrary number of digits.
Here's your implementation converted to use BigDecimal
:
public String fibo(int x){
BigInteger[] arr = new BigInteger[x+1];
arr[0]=BigInteger.ZERO;
arr[1]=BigInteger.ONE;
for (int i=2; i<=x; i++){
arr[i]=arr[i-2].add(arr[i-1]);
}
return arr[x].toString();u
}
请注意,返回类型必须是String(或BigInteger),因为即使是 x
的93的适度值也会产生一个对于任何java原语都太大的结果代表。
Note that the return type must be String (or BigInteger) because even the modest value of 93 for x
produces a result that is too great for any java primitive to represent.
这篇关于斐波那契系列f(93)处的数值具有负值,怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!