Java Longs中的Fibonacci计算显示为负数 [英] Fibonacci calculation in Java Longs shows up negative
问题描述
我的Fibonacci计算器工作正常,但是当达到更高的数字时,结果会显示为负数,因为如果它是整数
超过其最大值。
My Fibonacci calculator works fine, but when going up to higher numbers the result comes up negative, as it would if it was an Integer
over its max value.
它使用缓存 java.util.Map< Integer,Long>
。进入地图
的所有内容都是预期的,但是当打印出来时,我得到了对于291:
It is working with a cache java.util.Map<Integer, Long>
. Everything that goes into the Map
is exactly what is expected, but when printing it out I get e.g. for 291:
-784134397488903422
根据 http ://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibCalcX.html ,它应该是:
2923602405716568564338475449381171413803636207598822186175234
我的<$ c $似乎出了问题c>长 s,但我不确定,到底是什么。有人可以指出我正确的方向吗?
It seems something goes wrong with my Long
s, but I am not sure yet, what exactly. Could someone please point me in the right direction?
地图
条目的值:
http://pastebin.com/uje07Ays
推荐答案
我认为你高于可以存储在Java用于long类型的有符号64位整数中的最大long值,有关Long和Java API的更多信息: http://docs.oracle.com/javase/7/docs/api/java /lang/Long.html 。
I think you are above the maximum long value that can be stored in a signed 64 bits integer used by Java for the long type, more information about Long and thesein the Java API: http://docs.oracle.com/javase/7/docs/api/java/lang/Long.html.
64位有符号整数的最大正值为2 ^ 63 -1: 9 223 372 036 854 775 807
,您的值似乎已达到此限制,如果有符号整数的最高位为1,则有符号整数将变为负数(有关详细信息,请参阅2补码整数: http://en.wikipedia.org/wiki/Two%27s_complement )。
The maximum positive value for a 64 bits signed integer is 2^63 -1: 9 223 372 036 854 775 807
, your value seems to have reach this limit and if the highest bit of a signed integer is 1, then the signed integer become negative (see 2 complement integer for more details: http://en.wikipedia.org/wiki/Two%27s_complement).
您需要使用BigInteger来获得任意精度的整数 http ://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html 。
You need to use BigInteger to have arbitrary-precision integers http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html.
这篇关于Java Longs中的Fibonacci计算显示为负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!