Free, tested & ready to use examples! Web anyexample.com

AnyFormat.io - convert files and webpages to any format!

# Java prime number check (primality test)

 abstract Prime number is a natural number that has exactly two (distinct) natural number divisors, which are 1 and the prime number itself. Here is a trivial Java function for prime number test.
 compatible • Nearly any JDK version
• To test for primality for number n we need to check if any number from 2 to square root of n divides n.

For a greater speed there is quick-check with 55 precomputed primes and then (if result is still unknown) checking with every odd number from 55-th prime (257) to n/16 (for any number > 256, square root of n less than n/16)

source code: Java
```
public class AePrime {

public static boolean checkPrime(int n) {
int primes55[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,
73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,
181,191,193,197,199,211,223,227,229,233,239,241,251,257};

for(int i=0;i<55;i++) {
if (n%primes55[i] == 0) {
if (n == primes55[i]) {
return true;
}
else {
return false;
}
}
}

int maxtest = n/16;

for(int i=259; i<maxtest; i+=2)
if (n%i == 0)
return false;

return true;
}
}
```

To illustrate function usage, here is a program which outputs first 7 Mersenne primes.

Note, that it is impossible to use this function for checking Mersenne numbers of higher orders, because of integer type limitations and direct prime checking algorithm implementation.

source code: Java
```
public class Ex01 {
// Mersenne number is a number that is one less than a power of two
// Mersenne prime is a Mersenne number that is a prime number
public static void main(String[] args) {
int power_of_two = 2; // staring with 2^2, because 1 is not
// prime number
for(int n=2; n<31; n++) {
int mersenne = power_of_two - 1;
if (AePrime.checkPrime(mersenne)) {
System.out.print("Found Mersenne prime: ");
System.out.print(mersenne);
System.out.println(" (n = " +  String.valueOf(n) + ")");
}
power_of_two *= 2;
}
}
}
```

This program should output following:

```
Found Mersenne prime: 3 (n = 2)
Found Mersenne prime: 7 (n = 3)
Found Mersenne prime: 31 (n = 5)
Found Mersenne prime: 127 (n = 7)
Found Mersenne prime: 8191 (n = 13)
Found Mersenne prime: 131071 (n = 17)
Found Mersenne prime: 524287 (n = 19)
```

 warning • function AePrime.checkPrime use Java int type and cannot operate on numbers outside its range (-231..232-1)
•  tested • JDK 1.5
•