Friday, 11 January 2019

Java program to print the first n prime numbers

          In previous post, I have written the code to check the given integer is a palindrome or not. Today's post, writing a java code to display the first n prime numbers. n can be any integer number and greater than 1.

The prime number is a number that is divisible only by itself and 1. The 1 is not a prime number but 2 is a first prime number and it's even number.

First few prime numbers are, 2,3,5,7,11,13,17,19,23..... 

Example:-

n=10, (first 10 prime numbers)
Expected output :--2,3,5,7,11,13,17,19,23,29.

PrimeNumbers.java,

package com.example;

class PrimeNumbers {
 
    public static void main(String args[]) {
       
           int num = 3;
           boolean prime = true;
           System.out.println("The first 10 prime numbers are:--");
           System.out.println(2);          // first prime number
           for ( int i = 2 ; i <=10 ; ) {
                 for ( int j = 2 ; j <= Math.sqrt(num) ; j++ ) {
                        if ( num%j == 0 ) {
                               prime = false;
                               break;
                        }
                 }
                 if (prime) {
                        System.out.println(num);
                        i++;                          //if number is prime, increment i value
                 }
                 prime = true;
                 num++;
          }         
     }
}

Output:--
The first 10 prime numbers are:--
2
3
5
7
11
13
17
19
23
29


Related Posts:--
1) Java Program to check the given number is a palindrome or not
2) Write a Java program to print the Floyd's triangle
3) Java Program for Bubble Sort in Ascending and Descending order
4) Java Program to Reverse a Linked List using Recursion and Loops
5) Java Program to Count Occurrence of Word in a Sentence
6) How to Remove duplicates from ArrayList in Java

No comments:

Post a comment