Prime Number Program in Java
Prime number is a number which is divisible by itself.
We can write this program in multiple ways but it will reduce the performance for
larger numbers. Here we define one of faster and optimised way to check if number is prime or not.
public boolean isPrime(int value) {
if(value == 2)
return true;
if(value == 2)
return true;
if (value % 2 == 0)
return false;
for (int j = 3; j <= Math.sqrt(value); j+=2) {
if (value % j == 0) {
return false;
}
}
return true;
}
In this function, we first check if number is divisible by 2 or not. If not then no need to check with any other even numbers, So in for loop we increment value by 2. We use sqrt(value) as upper limit as if value is multiple of two number like a and b, then one of this number will be always less than square root value. So by using sqrt as upper limit, we will reduce time to check if number is prime or not.
This will output 2 as not being prime.... And i believe you posted the same code over stack overflow.. please rectify it
ReplyDeleteYes this will not. As this program was written to find prime number in lesser time keeping that in mind that 2 is prime number.
DeleteI have updated program with your suggestion.