Java比较整数和bigInteger

Pro*_*ogo 13 java biginteger bigint

如何比较的intBigInteger在Java中?我特别需要知道a int是否小于a 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;
};
Run Code Online (Sandbox Code Playgroud)

谢谢.

Joe*_*Joe 22

如何在Java中将int与BigInteger进行比较?我特别需要知道int是否小于BigInteger.

int成一个BigInteger比较之前:

if (BigInteger.valueOf(intValue).compareTo(bigIntegerValue) < 0) {
  // intValue is less than bigIntegerValue
}
Run Code Online (Sandbox Code Playgroud)

  • 用于将int转换为BigInt的+1,反之亦然.可能想提一下原因 (2认同)

Am_*_*ful 5

代替

if (x == BigInteger.ZERO || x == BigInteger.ONE) {
    return x;
Run Code Online (Sandbox Code Playgroud)

你应该使用:-

if (x.equals(BigInteger.ZERO) || x.equals(BigInteger.ONE)){
return x; 
Run Code Online (Sandbox Code Playgroud)

另外,您应该首先将 Integer 更改为 BigInteger,然后进行比较,如Joe他的回答中所述:

 Integer a=3;
 if(BigInteger.valueOf(a).compareTo(BigInteger.TEN)<0){
    // your code...
 }
 else{
    // your rest code, and so on.
 } 
Run Code Online (Sandbox Code Playgroud)