I got carried away recently with simple numbers and I needed a program to check the number for simplicity.
I check a huge number of numbers and work outside of long. First time working with BigInteger. Therefore, I would be happy to hear opinions about the effectiveness of the code. Is it possible to increase productivity somewhere?
The algorithm is simple:
- check whether 0,1,2 is equal to or less than zero.
- check whether it is divisible by at least one odd starting from 3 to the square root of the number itself.
Code:
public static boolean isPrime(BigInteger number) { if (number.compareTo(new BigInteger("0")) < 0) throw new IllegalArgumentException("The number should be positive"); if (number.toString().equals("1") || number.toString().equals("0")) return false; // if the number is even return FALSE, unless the number is "2". if (isEven(number)) { if (number.toString().equals("2")) { return true; } return false; } long limit = sqrt(number).longValue(); // A loop for searching a divider. If no divider found - return "true". for (long i = 3; limit >= i; i += 2) { // if (number % i == 0) if (number.mod(new BigInteger(String.valueOf(i))).toString().equals("0")) { // System.out.println("The first divider is " + i); return false; } } return true; } public static boolean isEven(BigInteger number) { if ((number.and(new BigInteger("1"))).toString().equals("0")) return true; else return false; } public static BigInteger sqrt(BigInteger N) { final BigInteger TWO = new BigInteger("2"); BigInteger result = N.divide(TWO); while (result.multiply(result).subtract(N).compareTo(BigInteger.ONE.divide(new BigInteger("100000000"))) > 0) result = result.add(N.divide(result)).divide(TWO); return result; }
isProbablePrime(), and then check with any test of simplicity that it is really a simple number. - Arsenicum