Friday, 11 January 2019

Java Program to Print the First n Prime Numbers

           In the previous post, I explained how to check whether a given integer is a palindrome. In today's post, we will write a Java program to display the first n prime numbers, where n can be any integer greater than 1.

A prime number is a number that is divisible only by 1 and itself. The number 1 is not a prime number, while 2 is the first prime number and the only even prime number.

The first few prime numbers are:

2, 3, 5, 7, 11, 13, 17, 19, 23, ...

Example

Input:

n = 10

Output (first 10 prime numbers):

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