Java比较整数和bigInteger
如何在 Java 中比较 int
与 BigInteger
?我特别需要知道 int
是否小于 BigInteger
。这是我正在使用的代码:
private static BigInteger two = new BigInteger("2");
private static BigInteger three = new BigInteger("3");
private static BigInteger zero = new BigInteger("0");
public static BigInteger bigIntSqRootCeil(BigInteger x) throws IllegalArgumentException {
if (x.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Negative argument.");
}
if (x == BigInteger.ZERO || x == BigInteger.ONE) {
return x;
}
BigInteger two = BigInteger.valueOf(2L);
BigInteger y;
for (y = x.divide(two);
y.compareTo(x.divide(y)) > 0;
y = ((x.divide(y)).add(y)).divide(two));
if (x.compareTo(y.multiply(y)) == 0) {
return y;
} else {
return y.add(BigInteger.ONE);
}
}
private static boolean isPrimeBig(BigInteger n){
if (n.mod(two) == zero)
return (n.equals(two));
if (n.mod(three) == zero)
return (n.equals(three));
BigInteger m = bigIntSqRootCeil(n);
for (int i = 5; i <= m; i += 6) {
if (n.mod(BigInteger.valueOf(i)) == zero)
return false;
if(n.mod(BigInteger.valueOf(i + 2)) == zero)
return false;
};
return true;
};
谢谢。
How do I compare an int
with a BigInteger
in Java? I specifically need the know if an int
is less than a BigInteger
. Here is the code I am using:
private static BigInteger two = new BigInteger("2");
private static BigInteger three = new BigInteger("3");
private static BigInteger zero = new BigInteger("0");
public static BigInteger bigIntSqRootCeil(BigInteger x) throws IllegalArgumentException {
if (x.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Negative argument.");
}
if (x == BigInteger.ZERO || x == BigInteger.ONE) {
return x;
}
BigInteger two = BigInteger.valueOf(2L);
BigInteger y;
for (y = x.divide(two);
y.compareTo(x.divide(y)) > 0;
y = ((x.divide(y)).add(y)).divide(two));
if (x.compareTo(y.multiply(y)) == 0) {
return y;
} else {
return y.add(BigInteger.ONE);
}
}
private static boolean isPrimeBig(BigInteger n){
if (n.mod(two) == zero)
return (n.equals(two));
if (n.mod(three) == zero)
return (n.equals(three));
BigInteger m = bigIntSqRootCeil(n);
for (int i = 5; i <= m; i += 6) {
if (n.mod(BigInteger.valueOf(i)) == zero)
return false;
if(n.mod(BigInteger.valueOf(i + 2)) == zero)
return false;
};
return true;
};
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在比较之前将
int
转换为BigInteger
:Turn the
int
into aBigInteger
before comparing:而不是
您应该使用:-
另外,您应该首先将 Integer 更改为 BigInteger,然后进行比较,如
Joe< /code>
在他的回答中:
Instead of
You should use :-
Also, you should change the Integer first to BigInteger, and then compare, as mentioned by
Joe
in his answer:只需使用
biginteger.compare
:Just use
BigInteger.compare
: