English 中文(简体)
如何比较BigInteger的值以用作循环中的条件?
原标题:How do I compare values of BigInteger to be used as a condition in a loop?

我正在尝试比较一个BigInteger(基数)的值是否为>(大于)另一个BigInteger(素数)的值,如果a的值不等于1。如果a的值不为1,则它应该脱离循环。我应该如何比较它们?

Random ran = new Random();
BigInteger prime = new BigInteger(16,ran);
BigInteger base,a,one;
one = new BigInteger("1");

for (int i = 0; i < 65535; i++){

    while (base>prime){
        base = new BigInteger(16,ran);
    }
    a = base.modPow(prime.subtract(one),prime);
    System.out.println("a: "+a);    
    if (a != one){
        break;          
    }   
}
最佳回答

您可以使用BigInteger.compareTo(BigInteger)

在您的情况下,这将是而(base.compareTo(prime)>;0){…}

此外,终止条件应从if(a!=一)更改为if(!a.equals(one))BigInteger变量不一定引用同一对象(这就是==!=测试的全部内容)。

问题回答

由于BigInteger是对象,因此在使用相等运算符时应小心。现在,您正在执行引用比较(在这种情况下,很可能会失败)。您需要使用equals()compareTo()方法。

BigInteger有一个表示一的内置静态变量。使用equals()方法或compareTo()方法比较值:

if (!a.equals(BigInteger.ONE)) {
    ...
}

-或-

if (a.compareTo(BigInteger.ONE) != 0) {
    ...
}

希望能有所帮助!有关详细信息,请参阅此处:http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html

大概

while (base.compareTo(prime)>0){
//rest of your loop
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签