2014-09-13 116 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"); 
}