簡體   English   中英

Java比較整數和bigInteger

[英]Java compare integer and bigInteger

如何在Java中將intBigInteger進行比較? 我特別需要知道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;
};

謝謝。

如何在Java中將int與BigInteger進行比較? 我特別需要知道int是否小於BigInteger。

在比較之前將int轉換為BigInteger

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

代替

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

你應該使用: -

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

此外,您應該首先將Integer更改為BigInteger,然后進行比較,如Joe在其答案中所述:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM