简体   繁体   中英

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. I also want to make a JFrame for it.

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. 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. Here is pseudocode for a simple version of the Sieve of Eratosthenes; I'll leave it to you to translate to 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. 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.

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.

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.

In the inner loop, it is enough to iterate to the SQRT(N) instead of N. It can reduces a runtime a bit.

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). Prime numbers can be divisible only by two numbers: 1 and itself, so k have to be equals or less than 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);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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