Home »
Java »
Java Programs
Java program to check whether a given number is prime or not using recursion
Given a number, we have to check whether it is prime or not using recursion.
Submitted by Nidhi, on June 02, 2022
Problem statement
In this program, we will read an integer number from the user and then we will find whether the given number is prime or not using recursion.
Java program to check whether a given number is prime or not using recursion
The source code to check whether a given number is prime or not using recursion is given below. The given program is compiled and executed successfully.
// Java program to check whether a given number is
// prime or not using recursion
import java.util.*;
public class Main {
public static int checkPrime(int num, int i) {
if (i != 1) {
if (num % i != 0)
return checkPrime(num, i - 1);
return 0;
}
return 1;
}
public static void main(String[] args) {
Scanner X = new Scanner(System.in);
int num = 0;
int res = 0;
System.out.printf("Enter number: ");
num = X.nextInt();
res = checkPrime(num, num / 2);
if (res == 1)
System.out.printf("Number is prime.");
else
System.out.printf("Number is not prime.");
}
}
Output
Enter number: 23
Number is prime.
Explanation
In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods checkPrime(), main(). The checkPrime() is a recursive method that finds whether the given number is a prime number or not.
The main() method is the entry point for the program. Here, we read an integer number from the user and called the checkPrime() method to check given number is prime or not and printed the appropriate message.
Java Recursion Programs »