简体   繁体   English

Java素数

[英]Java Prime Numbers

I am trying to make a prime number list. 我正在尝试列出质数表。 I have coded it, but it only tells me that the prime numbers of 1 - 100 is 1. I am not sure why that is happening. 我已经对其进行了编码,但它仅告诉我1-100的质数是1。我不确定为什么会这样。 I also want to make a JFrame for it. 我也想为此制作一个JFrame。

import javax.swing.JOptionPane;

public class ProgrammingAssignment7 {
    public static void main(String[] args) {
        //Scanner Scan = new Scanner (System.in);
        //DECLARE VARIABLES

        int x = 1;
        int i = 1;
        int iNumber = 1;
        boolean bNotPrime = false;
        boolean bIsPrime = true;
        int iNumberToTest;
        int iPrimeCheck;
        int iCounter;
        int iResult = 1;
        int iFact = 1;
        int iLimit = 100;
        String OutputStr = null;

        System.out.println("Prime numbers between 1 and " + iLimit);

        //loop through the numbers one by one
        for(i=1; i < 100; i++) {
            bIsPrime = true;

            //check to see if the number is prime
            for(int j = 2; j < i ; j++) {
                if(i % j == 0) {
                    bIsPrime = false;
                    break;
                }
            }
        }

        // print the number
        if(bIsPrime) {
            OutputStr = "The Prime Numbers of 1 - 100 are: " + i + "\n";
        }

        JOptionPane.showMessageDialog(null, OutputStr, "PRIME NUMBERS", JOptionPane.INFORMATION_MESSAGE);

        //System.out.print(i + "\n" );
        System.exit(0);
    }
}

You are calling system.exit(0) in your for loop. 您正在for循环中调用system.exit(0)。 So that it will terminate the program after the first iteration. 这样它将在第一次迭代后终止程序。 Remove that line and then try to run program. 删除该行,然后尝试运行程序。 It will give you correct results. 它会给您正确的结果。

Besides fixing your code you should also fix your algorithm. 除了修复代码之外,您还应该修复算法。 You are using an algorithm called trial division, which will be uncomfortably slow as your limit increases. 您正在使用一种称为“试验划分”的算法,随着您的限额增加,该算法将变得缓慢。 Instead, you should use an algorithm called the Sieve of Eratosthenes, invented over two thousand years ago and still widely used today. 相反,您应该使用一种称为Eratosthenes筛网的算法,该算法是在2000年前发明的,至今仍在广泛使用。 Here is pseudocode for a simple version of the Sieve of Eratosthenes; 这是Eratosthenes筛网的简单版本的伪代码; I'll leave it to you to translate to Java: 我将它留给您翻译成Java:

function primes(n)
    sieve := makeArray(2..n, True)
    for p from 2 to n step 1
        if sieve[p]
           output p
           for i from p * p to n step p
               sieve[i] := False

Eratosthenes' algorithm begins by making a list of numbers form 2 to the maximum desired prime n , then enters an iterative phase. Eratosthenes的算法开始于生成从2到最大所需素数n的数字列表,然后进入迭代阶段。 At each step, the smallest uncrossed number that hasn't yet been considered is identified, and all multiples of that number, starting from its square, are crossed out; 在每个步骤中,都将标识尚未考虑的最小的未交叉数,并从该数的平方开始减去该数的所有倍数; this is repeated until no uncrossed numbers remain unconsidered. 重复此操作,直到没有未交叉的数字保持不变为止。 All the numbers that remain uncrossed are prime. 所有未交叉的数字都是质数。 The inner loop starts at p * p because any smaller composites must have already been crossed out by smaller primes. 内循环从p * p开始,因为任何较小的合成物都必须已经被较小的素数消除。

For example, to find the primes less than thirty, first report that 2 is prime and cross out 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26 and 28. Then 3 is uncrossed, so report it as prime and cross out 9, 12, 15, 18, 21, 24, and 27. Since 4 has been crossed out, the next uncrossed number is 5, so report it as prime and cross out 25. Finally, since 7 * 7 is greater than 30, the inner loop stops executing and the outer loop collects the rest of the primes: 7, 11, 13, 17, 19, 23 and 29. 例如,要查找少于30的素数,请首先报告2是素数,并舍去4、6、8、10、12、14、16、18、20、22、24、26和28。 ,因此将其报告为质数,并划掉9、12、15、18、21、24和27。由于已将4划掉,因此下一个未交叉的数字为5,因此将其报告为质数并划掉25。最后,由于7 * 7大于30,因此内部循环停止执行,并且外部循环收集其余的质数:7、11、13、17、19、23和29。

If you're interested in programming with prime numbers, I modestly recommend an essay at my blog, which among other things provides an optimized version of the Sieve of Eratosthenes. 如果您对使用质数编程感兴趣,我建议在我的博客上推荐一篇文章 ,该文章除其他外,还提供了Eratosthenes筛网的优化版本。

In the inner loop, it is enough to iterate to the SQRT(N) instead of N. It can reduces a runtime a bit. 在内部循环中,迭代到SQRT(N)而不是N就足够了。它可以稍微减少运行时间。

for(int j = 2; j < Math.sqrt(i) ; j++) {

}

Smart algorithm for writing out prime numbers from 1-100 (and also 1- [how many you want] - if you change 100 for another number). 聪明的算法,可以写出1到100之间的质数(也可以写成1- [想要多少个-如果您将另一个数字更改为100 )。 Prime numbers can be divisible only by two numbers: 1 and itself, so k have to be equals or less than 2. 质数只能被两个数整除:1和它本身,因此k必须等于或小于2。

for (int i=1; i<=100; i++) {
        int k = 0;
        for (int j=1; j<=i; j++ ) {
            if (i % j == 0) {
                k++;
            }
        }
        if (k <= 2) {
            System.out.println(i);
        }
    }

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

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