Solution Review: Check for Prime Number
This lesson provides a detailed review of the solution to the challenge in the previous lesson.
We'll cover the following...
Solution: Is it a Prime Number?
class ChallengeClass {public static boolean isPrime(int num, int i) {// First base caseif (num < 2) {return false;}// Second base caseelse if (i == 1) {return true;}// Third base caseelse if (num%i == 0) {return false;}// Recursive caseelse {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 primeif (result == true) {System.out.println(input + " is a prime number");}// Prints if the number is NOT a prime numberelse {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
maincode, we have defined an integer variable, namedinput, and a boolean variable, namedresult. -
The
resultvariable stores the output of theisPrimemethod. -
The first parameter in the
isPrimemethod is the number to be tested, namedinput. 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
Booleansince we want to check if the number is prime or not and it takes the two integers,numandi, as input parameters. -
num...