Search⌘ K

Solution Review: Check for Prime Number

Understand how to implement a recursive method in Java to determine if a number is prime. Explore the base cases for prime checking and how recursion iterates through possible divisors. This lesson helps you apply recursion concepts specifically for prime number problems in coding interviews.

Solution: Is it a Prime Number?

Java
class ChallengeClass {
public static boolean isPrime(int num, int i) {
// First base case
if (num < 2) {
return false;
}
// Second base case
else if (i == 1) {
return true;
}
// Third base case
else if (num%i == 0) {
return false;
}
// Recursive case
else {
return isPrime(num, i-1);
}
}
public static void main( String args[] ) {
int input = 13;
boolean result = isPrime(input, input/2);
// Print if the number is prime
if (result == true) {
System.out.println(input + " is a prime number");
}
// Prints if the number is NOT a prime number
else {
System.out.println(input + " is NOT a prime number");
}
}
}

Understanding the Code

In the code above, the method isPrime is a recursive method, since it makes a recursive call in the method body. Below is an explanation of the above code:

Driver Method

  • In the main code, we have defined an integer variable, named input, and a boolean variable, named result.

  • The result variable stores the output of the isPrime method.

  • The first parameter in the isPrime method is the number to be tested, named input. The second parameter, input/2, is half of the number to be tested.

  • Lines 28-30 and lines 32-34 print the type - prime or not prime - of the number based on the value of the result.

Recursive Method

  • The return type of this method is Boolean since we want to check if the number is prime or not and it takes the two integers, num and i, as input parameters.

  • num ...