Skip to content

Instantly share code, notes, and snippets.

@aadipoddar
Created April 7, 2022 13:18
Show Gist options
  • Select an option

  • Save aadipoddar/bc9b98987f5365a82fcf8ed54d85f111 to your computer and use it in GitHub Desktop.

Select an option

Save aadipoddar/bc9b98987f5365a82fcf8ed54d85f111 to your computer and use it in GitHub Desktop.
Program to check whether the number is prime or not using recursion.
/*
Write a program to accept a number using int accept() function
and check whether the number is prime or not using recursion.
*/
import java.util.*;
class PrimeCheckRecursive {
int accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
return sc.nextInt();
}
boolean isPrime(int n, int k) {
if (n == 1)
return false;
else if (n == k)
return true;
else if (n % k == 0)
return false;
else
return isPrime(n, k + 1);
}
public static void main(String[] args) {
PrimeCheckRecursive pcr = new PrimeCheckRecursive();
if (pcr.isPrime(pcr.accept(), 2))
System.out.println("Number is prime");
else
System.out.println("Number is not prime");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment