Given a number the task is to check whether it is Prime Number or not using recursion.
Prime Number is a number which is only divisible by 1 and the number itself i.e., it has no factors other than 1 and itself.
Example 1: 7 is only divisible by 1 and itself only. Hence it is a Prime Number.
Example 2: 4 is divisible by 1 and 2 and 4. Hence it is not a Prime Number.
Java
import java.util.*;
public class PrimeRec
{
public int isPrime(int n,int i)
{
if(i==1)
{
return 1;
}
else if(i==0||n%i==0)
{
return 0;
}
else
{
return isPrime(n,i-1);
}
}
public static void main(String args[])
{
int n=0;
Scanner sc=new Scanner(System.in);
PrimeRec ob=new PrimeRec();
System.out.print("Enter a number: ");
n=sc.nextInt();
if(ob.isPrime(n,n-1)==1)
{
System.out.println(n+" is a Prime Number");
}
else
{
System.out.println(n+" is not a Prime Number");
}
}
}Java