Program to check whether entered number is Prime Number or Not (Java)

So today we are going to write program that checks whether a number entered by the user is Prime Number or Not. So this is a very simple program and it does not require much logic to write this program, as Prime Numbers are those which are divisible by 1 and the number itself.
So lets get started...


Q. Write a program that accepts an integer from the user and checks whether the entered number is Prime Number or Not.
[Prime Number is a number that is divisible only by 1 and itself.]
For Example: 2, 3, 5, 7, 11, etc...

Solution:
123456789101112131415161718192021222324252627 import java.util.*;
 class CheckPrimeNumber
 {
     public static void main(String[] args)
     {
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a number: ");
         int n = sc.nextInt();
         int count = 0;
         for(int i = 1;i <= n;i++)
         {
             if(n%i == 0)
             {
                 count++;
             }
         }
         if(count == 2)
         {
             System.out.println(n + " is a Prime Number");
         }
         else
         {
             System.out.println(n + " is not a Prime Number");
         }
     }
 }

Code Written in BlueJ
Output:
1234Enter a number: 
5
5 is a Prime Number

Output in BlueJ

Variable description used in program:
int n - It is used to accept a number from user.
int count - It is used to count the divisibility of number "n" i.e., To count its factor.
Explanation:
In this program "int n" is used to accept a number from the user and "int count" is used to count the factors of the number entered by the user i.e., int n. I have used Scanner class to accept the number from the user or you can use parameters or BufferReader, it is upto you. Then we used for() loop to find the factors of "int n" and to count the number of factors we used a counter variable i.e., int count. And after for() loop we used if-else statement, as a prime number has only 2 factors so we the statement according to this in if-else statement. And this is how our program works perfectly.

So that is it for the Prime Number program. Hope you find it useful and if you have any query do comment in the comment box and I will try to solve your query. Will see you on next program.

Thank You.
Program to check whether entered number is Prime Number or Not (Java) Program to check whether entered number is Prime Number or Not (Java) Reviewed by Get2Know on October 07, 2020 Rating: 5

No comments:

Powered by Blogger.