In this article, you'll learn to check whether a number is prime or not. This is done using a for loop and while loop in Java.
To understand this example, you should have the knowledge of the following Java programming topics:
- Java while and do...while Loop
- Java for Loop
A prime number is a number that is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.
Note : 0 and 1 are not Prime Numbers. The 2 is the only even prime number because all the other even numbers can be divided by 2.
Example : Check Prime Number using For Loop
import java.util.Scanner;
public class Prime {
public static void main(String args[]){
Scanner s1 = new Scanner(System.in);
System.out.println("Enter a number");
int a = s1.nextInt();
int i,fact,ctr=0;
for(i=1;i<=a;i++){
if (a % i == 0) {
ctr++;//Counts the number of factors
}
}
if(ctr==2){
System.out.println("Prime");
}
else{
System.out.println("Not Prime");
}
}
}
Video:
Example : Check Prime Number using While Loop
import java.util.Scanner;
class PrimeNumbers {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("Enter a number");
int a = s1.nextInt();
int n = 2;
int ctr = 0;
while (n <= a / 2) {
if (a % n == 0) {
ctr++;
break;
}
n++;
}
if (ctr == 0 ) {
System.out.print(a + " is a prime number ");
} else {
System.out.print(a + " is not a prime number ");
}
}
}