Prime Number Generator Logic

后端 未结 15 2234
旧时难觅i
旧时难觅i 2021-01-07 04:10

I am supposed to make a class PrimeNumberGenerator which has a method nextPrime that will print out all prime numbers up to a number the user input

15条回答
  •  攒了一身酷
    2021-01-07 04:49

    Try this code to generate prime number series

    public class prime1 {

    public static void main(String[] args) {
    
        int max = 100;
    
        System.out.println("Generate Prime numbers between 1 and " + max);
    
        // loop through the numbers one by one
        for (int i = 1; i < max; i++) {
    
            boolean isPrimeNumber = true;
    
            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }
    
            // print the number if prime
            if (isPrimeNumber) {
                System.out.print(i + " ");
            }
        }
    
    }
    

    }

提交回复
热议问题