How To - Test for Prime Numbers
Advertisements
Description:
The below methods are the easiest and fastest ways to test for prime numbers.
Method 1: Simplest Way (in terms of Coding)
Here is the code for this method:
public boolean isPrime(int n) {
for (int i = 2; i <= n; i++) {
if (n % i == 0) {
return false; // n is not a prime number.
}
}
return true; // n is a prime number.
}
Method 2: Fastest Way (in terms of Processing)
Here is the code for this method:
public boolean isPrime(long n) {
// fast even test.
if(n > 2 && (n & 1) == 0)
return false;
// only odd factors need to be tested up to n^0.5
for(int i = 3; i * i <= n; i += 2)
if (n % i == 0)
return false;
return true;
}
java_strings.htm
Advertisements