Java Program to Check Whether a Given Number Is Prime or Not Using Recursion

You are currently viewing Java Program to Check Whether a Given Number Is Prime or Not Using Recursion

Java program to check whether a given number is prime or not using recursion

// 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.

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply