用于检查素数的GUI

时间:2014-04-10 17:23:16

标签: java swing user-interface boolean

我已更新代码以反映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;
  }

}

2 个答案:

答案 0 :(得分:0)

尝试这个来检查素数

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.";

答案 1 :(得分:0)

你的IsPrime方法需要很大的内容 - 但是使用标准整数进行所有检查 - 如果你的用户想要变得困难,这会导致问题。这是用于检查一般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;
      }