Java Program to Display All the Prime Numbers up to N

Prime number

Java program to display all primes up to $n$ has been shown here. Here $n$ is a positive integer. For example if $n = 20$, we get all the prime numbers less or equal to $20$ i.e. $2, 3, 5, 7, 11, 13, 17, 19$. The algorithm, pseudocode and time complexity of the program have been shown below.






1. Algorithm to display all primes up to N


1. Take input of a positive number n as limit.

2. Repeat step 3 to 5, for each i $\in$ [2, $n$]

3. Check for each j $\in$ [2, $\sqrt{i}$], if i is divisible by any value of j

4. If step 3 is true for atleast one j, then i is not a prime.

5. If step 3 is false for each i, then display i as a prime




2. Pseudocode to display all primes up to N


Input : A postive number $n$ as limit

Output : All the prime number below $n$

1. Procedure checkPrime($n$):

2. Repeat for $i \in [2, n]$:

3. $flag \leftarrow 0$

4. Repeat for $j \in [2, \sqrt{i}]$:

5. If $i \mod j$ == 0:

6. $flag \leftarrow 1$

7. break

8. If $flag == 0$:

9. Print $i$

10. End Procedure





3. Time complexity to display all primes up to N


Time Complexity: O(n$\sqrt{n}$)

Where n is the total count of positive numbers and O($\sqrt{n}$) is the time to check primality of each number.





4. Java Program & output to display all primes up to N

Code has been copied
/****************************
    alphabetacoder.com
Java program to find all the 
prime numbers up to n 
*****************************/

import java.util.Scanner;
import java.lang.Math;

class Main {
    public static void main(String args[]) {
        // declare object of Scanner class
        Scanner sc = new Scanner(System.in);

        // declare variables
        int n, i, j, flag = 0;

        //take input of the order of first matrix
        System.out.print("Enter the limit = ");
        n = sc.nextInt();

        // display result
        System.out.print("List of primes upto " + n + ": ");
        // consider each number from i = 2
        // to n for primality test
        for (i = 2; i <= n; i++) {
            // initialize variable
            flag = 0;

            //check if current i is prime or not
            //If i has divisor between 2 and
            // square root of i, then 
            // i is not prime else i is prime
            for (j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    flag = 1; // mark as not prime
                    break; // exit from loop
                }
            }
            // flag = 0 means i is prime.
            // Display i
            if (flag == 0)
                System.out.print(i + " ");
        }
    }
}

Output


Enter the limit = 40

List of primes upto 50: 2 3 5 7 11 13 17 19 23 29 31 37