JAVA program to generate first n prime numbers

 

JAVA program to generate first n prime numbers

This JAVA program is used to generate first n prime numbers.

Example first 4 prime nos would be 2,3,5,7.

Logic

We have taken a while loop which acts like a counter means as soon as we get a prime number the i value will be incremented.Then we have taken a for loop for taking every number.the if condition is done so as to make sure that if the no is prime or not.Flag variable is used which signals us that if number taken is prime or not.

Dry Run of the Program

Take input ‘n’ to generate first n prime nos.Let us take n=3.

1st iteration while(i<=n) i.e. while(1<=3)

for(count=2;count<=p-1;count++) i.e. for(count=2;count<=1;count++) as p=2

we do not enter the if as count is not <=1 but it is >1.So we exit the for loop

if(flag==1)  As flag=1

i++;  i.e. i=2; and print p , i.e. p=2

p++ ; p=3;

2nd iteration while(i<=n) i.e. while(2<=3)

for(count=2;count<=p-1;count++) i.e. for(count=2;count<=2;count++) as p=3

We  check the IF condition  if(p%count==0)  i.e. if(3%2==0)

this condition is false so we do not execute the if statements.

We exit this for loop as now when count is incremented count=3 which is>=2

if(flag==1)  As flag=1

i++;  i.e. i=3; and print p , i.e. p=3

p++;  i.e. p=4

3rd iteration while(i<=n) i.e. while(3<=3)

for(count=2;count<=p-1;count++) i.e. for(count=2;count<=3;count++) as p=4

We  check the IF condition  if(p%count==0)  i.e. if(4%2==0)

this condition is true so we execute the if statements.

Set flag variable to 0 i.e. flag=0 and break;

We exit this for loop as we executed the break statement.

if(flag==1)  As flag=0 we do not execute the if statements

We only increment the value of p;  p++;  p=5

Same procedure as above…

While loop will end here as i=4 which is greater than 3

So the output we get will be 2,3,5 which are first n prime numbers.

Program

import java.util.*;

class primeN
{
	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		int  i,n,p,count,flag;

		System.out.println("Enter the number of prime terms you want!");
    		n=sc.nextInt();
    		System.out.println("First "+n+" prime numbers are :-"); 

		p=2;
    		i=1; 
	    	while(i<=n)
    		{
        		flag=1;
        		for(count=2;count<=p-1;count++)
        		{
            			if(p%count==0)  //Will be true if p is not prime
            			{
	            			flag=0;
	            			break;      //Loop will terminate if p is not prime
            			} 	 
        		}
            		if(flag==1)
            		{
               	 		System.out.print(p+" ") ;
	            		i++;
            		}
        		p++;
    		}
	}
}

Output

Share Me!