java Int 到 BigInteger,有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32142913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Int to BigInteger, what's the difference?
提问by Stephen
I transfer the modExp function from int to BigInteger, but the result is different, what the different of these two functions?
我把modExp函数从int转为BigInteger,结果不一样,这两个函数有什么区别?
Thanks!!!
谢谢!!!
The function with BigInteger, the result always 1:
带有 BigInteger 的函数,结果始终为 1:
public static BigInteger modExp(BigInteger a, BigInteger b, BigInteger n) {
BigInteger two = new BigInteger("2");
if (b == BigInteger.ZERO)
return BigInteger.ONE;
BigInteger t = modExp (a, b.divide(two), n);
BigInteger c = (t.pow(2)).mod(n);
if (b.mod(two) == BigInteger.ONE)
c = (c.multiply(a)).mod(n);
return c;
}
The function with int:
带int的函数:
public static int modexp(int a, int b, int n) {
if (b == 0) return 1;
long t = modexp(a, b/2, n); // use long for intermediate computations to eliminate overflow
long c = (t * t) % n;
if (b % 2 == 1)
c = (c * a) % n;
return (int) c;
}
The function is to calculate a^b mod p
, For example:
功能是计算a^b mod p
,例如:
a=4 b=6 p=11 result1 = 1 result2 = 4
a=9 b=2 p=11 result1 = 1 result2 = 4
a=5 b=6 p=23 result1 = 1 result2 = 8 ...
回答by Danail Alexiev
The obvious difference is the difference between int
and BigInteger
.
最明显的区别是之间的差异int
和BigInteger
。
One difference is that int
is a primitive type and BigInteger
is a reference type. As such, it is better to use equals() when comparing BigInteger
s. So b == BigInteger.ZERO
should be BigInteger.ZERO.equals(b)
.
一个区别是它int
是原始类型和BigInteger
引用类型。因此,在比较BigInteger
s时最好使用 equals() 。所以b == BigInteger.ZERO
应该是BigInteger.ZERO.equals(b)
。
BigInteger is more suited to working with big numbers and will prevent you running into problems with overflowing the max int
value, supported by Java.
BigInteger 更适合处理大数字,并且可以防止您遇到int
Java 支持的最大值溢出问题。
Overflowing may be the cause you are getting a different result from the two functions as well. When this occurs, it doesn't cause any exception to be thrown, but the values of the int
s get messed up.
溢出可能是您从这两个函数中得到不同结果的原因。发生这种情况时,不会引发任何异常,但int
s的值会混乱。
回答by Jib'z
In java int can count from -2^31 up to 2^31-1 because int are coded over 4 bytes but long can count from -2^63 up to 2^63-1 because long are coded over 8 bytes.
在 java 中,int 可以从 -2^31 计数到 2^31-1,因为 int 被编码超过 4 个字节,但 long 可以从 -2^63 计数到 2^63-1,因为 long 被编码超过 8 个字节。
In the second method with this :
在第二种方法中:
return (int) c;
you may loose data (the 4 first byte)
您可能会丢失数据(第 4 个字节)
That could explain why your result are different because BigInteger are coded over much more byte than long
这可以解释为什么你的结果是不同的,因为 BigInteger 是用比 long 多得多的字节编码的