Java Programs

Print first n Prime number Program in Java

In this tutorial, we are going to learn writing java program to print all the prime numbers that are smaller than or equal to the number given as an input by the user.

Problem Statement

For any number that is input by the user, we have to print all the prime numbers. For example

Case1: If the user inputs number 12
then the output should be ‘2, 3, 5, 7, 11’.
Case2: If the user inputs a number 51.
then the output should be ‘2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ’.

What is Prime Number?

Prime Numbers are the numbers that have only 2 factors 1 and the number itself. It is only defined for the number which is greater than ‘1’. ‘2’ is the smallest prime number.

Some examples

  1. 5 is a prime number because only factors of 5 are ‘1 and 5’.
  2. 11 is a prime number because only factors of 11 are ‘1 and 11’.
  3. 10 is not prime because the factors of 10 are ‘ 1,2,5 and 10’.

Java Program to Print First n Prime Number

import java.util.*;

public class Main {

public static void main(String[] args) {

    int i=0,n,temp,temp1=1;
    Scanner sc = new Scanner(System.in);
    System.out.println("Java Program to print first n prime numbers ");
    n= sc.nextInt();
    System.out.println("Prime numbers are before "+n);

    while(temp1<=n){
        temp=0;
        for(i=2;i<=(temp1/2);i++){
            if(temp1%i==0)
            {
                temp=1;
                break;
            }
        }
        if(temp==0){
            System.out.println(temp1);
        }
        temp1++;
        }
    }
}

Output

Java Program to print first n prime numbers 
5
Prime numbers are before 5
1
2
3
5

Explanation

The input number is 9, so our program will check all the numbers smaller than 9 and greater than 0. The numbers that do not have any other factor other than 1 and itself, i.e. prime numbers which are smaller than 9 are 1,2,3,5, and 7.

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs