In this exercise we were asked to test a number for primality and print the results. Additionally – in the case the number is composite – the smallest divisor different from 1 should be printed out. Negative input values shall not pre processed and result in a message.
The second part of that task to improve the performance of the test and wipe out as many redundant and unnecessary comparisons as possible. We were not allowed to use any built-in methods to check for primality.
I have concerns mainly about properly handling input I’m rejecting and naming things (talking about result
here).
/**
* Tests a positive integer for primality.
* Prints out whether a number is prime, composite or neither.
*/
public class PrimalityTest {
public static void main(String[] args) {
// We only test one number, so no other arguments are allowed.
if (args.length > 1) {
System.out.println("Too many arguments. Please enter a positive integer prime canidate.");
System.exit(1);
}
int primeCandidate = 0;
try {
primeCandidate = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("The entered value was not an integer.");
System.exit(1);
}
if (primeCandidate < 0) {
System.out.println("Negative numbers are never prime.");
System.exit(1);
}
int result = smallestDivisor(primeCandidate);
if (result == -1) {
System.out.println(primeCandidate + " is prime.");
} else if (result == 1 || result == 0) {
System.out.println(primeCandidate + " is neither prime nor composite.");
} else {
System.out.println(primeCandidate + " is composite and has the smallest divisor " + result + ".");
}
}
/**
* Returns the smallest divisor of composite numbers or
* 1 if the number is 1 (not composite, not prime) or
* -1 if the number is prime (not composite).
*/
public static int smallestDivisor(int primeCandidate) {
if (primeCandidate == 0 || primeCandidate == 1) {
return primeCandidate;
} else if (primeCandidate <= 3) {
// 2 and 3 are prime.
return -1;
} else if (primeCandidate % 2 == 0) {
// All numbers greater 2 and divisable by 2 are not prime and the smallest divisor is 2
return 2;
} else if (primeCandidate % 3 == 0) {
// All numbers greater 3 and divisable by 3 are not prime and the smallest divisor is 3
return 3;
} else {
// Checks divisability of numbers in the form of 6k+1 and 6k-1.
// It starts with: 5 and 7, 11 and 13, 17 and 19, 23 and 25, ...
for (int i = 5; i * i <= primeCandidate; i += 6) {
if (primeCandidate % i == 0) {
return i;
} else if (primeCandidate % (i + 2) == 0) {
return i + 2;
}
}
// No divisor found, the number is prime.
return -1;
}
}
}
System.out.format()
directly. What did you have in mind? \$\endgroup\$