write a program to Check Whether a Given Number is Prime or Not
This program checks if the user-entered integer is prime or not. It does this by checking if the number is divisible by any integer other than 1 and itself. If the number has a factor other than 1 and itself, then it is not prime. If the number does not have any factors other than 1 and itself, then it is prime.
- Scanner input = new Scanner(System.in);: This creates a new Scanner object called input that reads user input from the console.
- System.out.print("Enter the Number :"); : This displays the message "Enter the Number :" on the console, prompting the user to enter an integer.
- int num = input.nextInt();: This reads an integer value entered by the user using the Scanner object and assigns it to the variable num.
- int i, count = 0; : This declares two integer variables i and count. i will be used in the for loop to check if the number is prime, and count will keep track of how many factors the number has.
- for(i=2; i<num; i++): This is a for loop that starts with i being initialized to 2 and continues until i is less than num. This loop will check if num is divisible by any number other than 1 and itself.
- if(num%i == 0) : This checks if num is divisible by i (i.e., num has a factor other than 1 and itself).
- { count++; break; }: If num is divisible by i, this increments the count variable by 1 and breaks out of the for loop. If count is greater than 0, then the number is not prime.
- if(count==0) System.out.println("This is a Prime Number."); : This checks if count is equal to 0, meaning the number is prime, and prints "This is a Prime Number." if it is.
- else System.out.println("This is not a Prime Number."); : If count is not equal to 0, this prints "This is not a Prime Number.", indicating that the number is not prime.
Source Code
import java.util.Scanner;
class Prime_Numbe
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the Number :");
int num = input.nextInt();
int i, count = 0;
for(i=2; i<num; i++)
{
if(num%i == 0)
{
count++;
break;
}
}
if(count==0)
System.out.println("This is a Prime Number.");
else
System.out.println("This is not a Prime Number.");
}
}
Output
Enter the Number :71
This is a Prime Number.