Prime Number JAVA program – Complete tutorial

Here we discuss the most commonly asked JAVA program in interviews at fresher level and experienced level and many of us not able to recall the prime number program . so First understand the concept of the Prime number and memorize it.

What is Prime Number ?
Prime number are the numbers that are not divisible by any number except 1 and itself. 0 and 1 are not prime numbers.

Pseducode of the Prime number program

1 ) Take the input as the number.
2) Now take any temp number and store number/2 in that number ( Numbers greater than input/2 are multiples of numbers less than input/2 . Lets say 14/2 = 7 so 8 is multiple of 4 )
3) Take a flag variable and set it to true.
4) Now check that input number is divisible by all number from 2 to input/2 ( use for loop for this ).
5 ) If input number is divisible any number then set flag = false.
6) Print the number as prime or non prime.

Below is the JAVA program explaining the same.

public class Prime_Numbers_Padhle {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Prime_numbers(1);
	
	}
	
	public static void Prime_numbers(int input)
	{
		boolean Prime_Number_flag = true ;
		int temp = input/2 ;
	for ( int i = 2 ; i <= temp ; i ++)
	{
		if ( input % i == 0 )
		{
			System.out.println(input + " is not prime number");
			Prime_Number_flag = false ;
			break;
		}
	}
	
	if ( Prime_Number_flag == true)
	{
		System.out.println(input + " is prime number");
	}

}
}

If you have any confusion regarding this please leave in the below comments .Hope you like the article and subscribe with us for the latest updated

Leave a Comment

Your email address will not be published. Required fields are marked *