2014-09-13 70 views
6

如何比较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; 
}; 

感谢。

+0

那么,为什么你认为不工作? – 2014-09-13 15:38:48

+0

@ E_net4嗯......我知道它为什么不起作用。我正在寻找解决方案。 – Progo 2014-09-13 15:50:48

+2

如果你要求的是“比较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

回答

16

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

打开intBigInteger比较之前:

if (BigInteger.valueOf(intValue).compareTo(bigIntegerValue) < 0) { 
    // intValue is less than bigIntegerValue 
} 
+1

用于将int转换为BigInt,反之亦然。可能想提到为什么 – Gus 2014-09-13 15:55:47

4

而不是

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

尽管这是问题代码段中的问题,但并不真正回答主要问题。 – 2014-09-13 15:39:57

1

只需使用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"); 
}