Java比较整数和大整数

20

在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;
};

谢谢。


那么,你为什么认为它不起作用呢? - E net4
@E_net4 嗯...我知道为什么它不起作用了。我正在寻找解决方案。 - Progo
3
如果你要求的是“将BigInt与int比较”,那么这将涉及到大量的代码。是否有其他问题需要解决?否则可以参考以下链接:http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html#compareTo(java.math.BigInteger) compareTo方法返回-1(小于),0(等于)或1(大于)。 - Gus
3个回答

36
在Java中,如何比较int和BigInteger?我需要知道int是否小于BigInteger。在比较之前,将int转换为BigInteger:
if (BigInteger.valueOf(intValue).compareTo(bigIntegerValue) < 0) {
  // intValue is less than bigIntegerValue
}

3
将整数转换为大整数,而不是反过来,进行这个+1操作。可能需要说明为什么。 - Gus

5
代替

if (x == BigInteger.ZERO || x == BigInteger.ONE) {
    return x;

你应该使用:

if (x.equals(BigInteger.ZERO) || x.equals(BigInteger.ONE)){
return x; 

此外,你应该先将整数更改为BigInteger,然后再进行比较,正如Joe在他的答案中提到的那样:
 Integer a=3;
 if(BigInteger.valueOf(a).compareTo(BigInteger.TEN)<0){
    // your code...
 }
 else{
    // your rest code, and so on.
 } 

1
虽然问题的代码片段中存在一个问题,但这并不能真正回答主要问题。 - E net4

3
只需使用BigInteger.compare方法:
int myInt = ...;
BigInteger myBigInt = ...;
BigInteger myIntAsABigInt = new BigInteger(String.valueOf(myInt));

if (myBigInt.compareTo(myIntAsABigInt) < 0) {
    System.out.println ("myInt is bigger than myBigInt");
} else if (myBigInt.compareTo(myIntAsABigInt) > 0) {
    System.out.println ("myBigInt is bigger than myInt");
} else {
    System.out.println ("myBigInt is equal to myInt");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接