Java program -5: Write a program which show the display of 15 prime number.

in #java7 years ago

package program;

import java.util.Scanner;

public class PrimeNumber{

public static void main(String [] args){

     int enterNumber ;
     int status = 1;
     int number = 3;
     Scanner input = new Scanner(System.in);
     System.out.print( " Enter the value of integer :__);

    enterNumber = input.nextInt();

   if(  enterNumber>= 1){

        System.out.println("First  " + enterNumber+ " prime numbers are : ");

        System.out.println(2);
     } 

     for( int i = 2; i <=  enterNumber; ){

         for(int j =2; j<= Math.sqrt(number) ; j++){

                if(number%j==0){

                      status = 0;
                      break;
                 }
           }
          if(status != 0){

                 System.out.println(number);
                 i++;
          }
         status = 1;
         number++;
    }
}

}

Input :
15

Output :
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47

prime_numbers_mug.jpg

Sort:  

good post bro...useful for students

It’s a good post, but you could be more thoughtful on the inner loop. You could use a step-size of at least 2. Or if the number is larger than 3, print 3 and use a step-size of 3. Cause the primes cannot be any multiples of those numbers. In fact you just have to check if they are divisible by smaller prime numbers. If not, it is a new prime. That’s a much more efficient way. But your way is also okay for little numbers.

Congratulations @afjal.softcare! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of posts published

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

friend you have made us happy...

Coin Marketplace

STEEM 0.24
TRX 0.25
JST 0.040
BTC 94242.56
ETH 3408.52
USDT 1.00
SBD 3.35