简体   繁体   English

用循环查找素数

[英]Find a prime number with loops

I'am new to Java and my homework was to make a program where the user input a number and the program check if the number is a prime number or not. 我是Java的新手,我的家庭作业是制作一个程序,用户在其中输入数字,然后程序检查数字是否为质数。

I have to use any loop and JOptionPane for input. 我必须使用任何循环和JOptionPane进行输入。

I've managed to write this code and it works: 我设法编写了这段代码,它的工作原理是:

import static javax.swing.JOptionPane.*;
public class Programmeringsoppgave5 {

    public static void main(String[] args) {
        int number = 0; 
        String readNumber = showInputDialog("Write a number and exit with ESC");

        while (readNumber != null){
        number = Integer.parseInt(readNumber);
            if (number != 0 && (number == 1 || number == 2)){
                System.out.println("Number " + readNumber + " is a prime number.");
            } else if (number % 2 == 0){
                System.out.println("Number " + readNumber + " is not a prime number.");
            } else if (number % 2 == 1){
                System.out.println("Number " + readNumber + " is a prime number.");
            }//end if-test
            readNumber = showInputDialog("Write a number and exit with ESC");
        }//end while    
    } //end method
}//end class

I was wondering if there was any easier or better ways to write this program? 我想知道是否有任何更简便或更好的方法来编写此程序?

To make sure a number is prime, you need to see whether it's divisible by any of the prime numbers below it. 为了确保数字是质数,您需要查看该数字是否可被其下面的任何质数整除。

So you can do something more like having an ArrayList of primes you've found so far, which starts with a hard-coded 2. 因此,您可以做更多的事情,例如拥有到目前为止找到的素数的ArrayList,它以硬编码2开头。

Then, you start looping from 3 up, and you test whether each new number is divisible by any of the primes already in your ArrayList. 然后,从3开始循环,然后测试每个新数字是否可被ArrayList中已有的质数整除。 If it's not, you add it and move on to the next. 如果不是,则将其添加并移至下一个。 If it is, then you just move forward. 如果是,那么您只需前进。

You do this until you get to the number in question. 您必须执行此操作,直到找到所涉及的号码。

There are a few optimizations you can perform. 您可以执行一些优化。 For example, when checking for numbers that are the factors of the current number, you only need to go up to sqrt(currNum). 例如,当检查作为当前数字的因数的数字时,仅需要增加sqrt(currNum)。

If you want to get fancy, you could implement the Sieve of Eratosthenes: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 如果您想花哨的话,可以实施Eratosthenes筛网: http : //en.wikipedia.org/wiki/Sieve_of_Eratosthenes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM