Validate prime number using Java
In order to validate prime number using Java, first of all, let’s see what is a prime number.
- A whole number greater than 1
- The only factors are 1 and itself.
- A factor is a whole number that can be divided evenly into another number.
- The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.
Example code: Validate prime number using java
//Validates if a given number is Prime number
public static boolean checkPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Discover more from Automation Script
Subscribe to get the latest posts sent to your email.