【问题标题】:Java compare integer and bigIntegerJava比较整数和大整数
【发布时间】:2014-11-07 14:31:44
【问题描述】:

如何比较 int 和 Java 中的 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 嗯...我知道它为什么不起作用。我正在寻找解决方案。
  • 如果您要求的是“将 BigInt 与 int 进行比较”,那将是很多代码。里面是否隐藏着另一个问题?否则:docs.oracle.com/javase/6/docs/api/java/math/…compareTo 返回 -1(小于)、0(等于)或 1(大于)

标签: java biginteger bigint


【解决方案1】:

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

在比较之前将int 转换为BigInteger

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

【讨论】:

  • +1 用于将 int 转换为 BigInt,反之亦然。可能想提一下原因
【解决方案2】:

代替

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.
 } 

【讨论】:

  • 虽然这是问题代码 sn-p 中的一个问题,但这并不能真正回答主要问题。
【解决方案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");
}

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2017-02-11
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多