Java Program for Prime Number

Here you will get java program for prime number.

A number is said to be prime number if it is only divisible by 1 or itself. For example 2, 3, 5, 11, 13, etc are prime numbers.

We can check a number is prime or not by following method.

If all the numbers between 2 to n/2 doesn’t divide n completely then n is prime otherwise not.

Java Program for Prime Number

import java.util.Scanner;

public class PrimeNumberJava {
	public static void main(String args[]){
		int n, i, flag = 1;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("enter a number: ");

		n = sc.nextInt();		
		
		for(i = 2; i <= n/2; ++i){
			if(n%i == 0){
				flag = 0;
				break;
			}
		}
		
		if(flag == 1){
			System.out.println("prime number");
		}
		else{
			System.out.println("not prime number");
		}
	}
}

 

Output

enter a number:
11
prime number

Leave a Comment

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