Java Program to check Given Number is Prime or not

EX: Write a Java Program to check given number is prime or not.


  What is prime number?

Prime number is a number that is greater than 1 and divided by 1 and itself only.
For example: 2, 3, 5, 7, 11, 13, 17, 19, 23... etc. are prime numbers.


Program:


import java.util.*;

public class PrimeNumber {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		int count = 0;
		System.out.println("Enter number: ");
		int num = sc.nextInt();
		
		if(num==0||num==1) {
			System.out.println(num+" is not prime number");
		}else {
		for(int i=1; i<=num;i++) {
			if(num%i==0)
				count++;
		}
		if(count>2)
			System.out.println("Given number is not prime");
		else
			System.out.println("Given number is prime");
		}
		
	}

}

Output:

Enter number: 
11
Given number is prime



No comments:

Post a Comment

If you have any doubts, please discuss here...👇