write a java program to input a number and test if it is a prime number
Today We will create a java program to take input of number and check weather it is a prime number or not using java So Lets Get Started
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
int number;
Scanner sc=new Scanner(System.in);
System.out.print("Enter number: ");
number=sc.nextInt();
int n=2, mid=number/2;
boolean primetest = true;
do {
if (number % n == 0) {
System.out.println("A factor "+n+" of "+number+" found!");
System.out.println("Hence NOT a prime number11");
primetest=false;
break;
}
n++;
}
while(n<=mid);
if(primetest==true){
System.out.println(number+" is a Prime Number");
}
}}
Explaining The Above Program Step By Step
- Firstly import scanner class to take input
- then I have created a class
- After that created a main function
- Create a variable number
- Create scanner object to take input
- Then i have printed Enter number
- After that i have checked the number is prime or not using do while loop
Today we have learned how to input a number and test if it is a prime number
Thank You