我已经更新了代码以反映BigInteger数字。但我现在收到了显示消息的错误。语法错误在IsPrime下。如何更改此字符串输出以向用户获得正确的显示消息?这是我的代码:
public static void main (String [] args){
//prompt user to input a number
String input = JOptionPane.showInputDialog("Enter number ");
// change string to int
int number = Integer.parseInt(input);
//display message to user of their results
BigInteger num = new BigInteger(input);
String output = number + " is" + (BigInteger(input) ? " " : " not ") + "a prime number: " + BigInteger(input);
JOptionPane.showMessageDialog (null, output);
}
public static Boolean IsPrime(BigInteger num) {
// check if number is a multiple of 2
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
i.add(new BigInteger("2"))) {
if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
}
您的IsPrime方法需要一个大的int,但使用标准int进行所有检查,如果您的用户想要变得困难,这将导致问题。这是用于检查一般BigIntegers素数的工作代码。
public static Boolean IsPrime(BigInteger num) {
// check if number is a multiple of 2
if (num.mod(new BigInteger("2")).compareTo(BigInteger.ZERO) == 0) {
return false;
}// if not, then just check the odds
for (BigInteger i = new BigInteger("3"); i.multiply(i).compareTo(num) <= 0; i =
i.add(new BigInteger("2"))) {
if (num.mod(i).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
return true;
}
试试这个来检查素数
boolean isPrime(int n) {
for(int i=2;2*i<n;i++) {
if(n%i==0)
return false;
}
return true;
}
一种更快速的方法来检查素数
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
--编辑--
根据您更新的问题和意见
试试这个
String output = number + " is" + (isPrime(number) ? " " : " not ") + "a prime number.";