如何比較int
與Java中的BigInteger
?我特別需要知道int
是否小於BigInteger
。這裏是我使用的代碼:Java比較整數和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;
};
感謝。
那麼,爲什麼你認爲不工作? – 2014-09-13 15:38:48
@ E_net4嗯......我知道它爲什麼不起作用。我正在尋找解決方案。 – Progo 2014-09-13 15:50:48
如果你要求的是「比較BigInt和int」,那麼這是很多代碼。那裏隱藏着另一個問題嗎?否則:http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html#compareTo(java.math.BigInteger)'compareTo'返回-1(小於),0(等於)或1(大於) – Gus 2014-09-13 15:51:42