Java Program to check a number is prime or not using recursion


In this program, you will learn how to check a number is prime or not using recursion in java.


Some list of prime numbers : 2 3 5 7 11 13 17

Example: How to check a number is prime or not using recursion in java.

import java.util.Scanner;

class Main {
    int p = 1;


    int checkPrime(int n, int i) {
        if (n % i == 0 && i <= n/2) {
            return p = 0;
        } else if (i <= n / 2) {
            checkPrime(n, i = i + 1);
        }

        return p;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number:");
        int n = sc.nextInt();

        Main obj = new Main();
        int p = obj.checkPrime(n, 2);

        if (p == 1) {
            System.out.println("Number is prime:" + n);
        } else {
            System.out.println("Number is not prime:" + n);
        }

    }
}

Output:

Enter a number:19
Number is prime:19

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.