Question
Check whether a number is prime number or not using recursion
Prime number is a number that is greater than 1 and divided by 1 or itself only. In other words, prime numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.
ENTER A NUMBER:13
13 IS PRIME NUMBER
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class primeNumber
{
public static boolean checkPrime(int n,int i)
{
if(n<=1)
{
return false;
}
else if(i==n)
{
return true;
}
else if(n%i==0)
{
return false;
}
else
{
return checkPrime(n,(i+1));
}
}
public static void main()
{
int num=0;
boolean isPrime=false;
Scanner sc=new Scanner(System.in);
System.out.print("ENTER A NUMBER:");
num=sc.nextInt();
isPrime=checkPrime(num,2);
if(isPrime==true)
{
System.out.println(num+" IS PRIME NUMBER");
}
else
{
System.out.println(num+" IS NOT PRIME NUMBER");
}
}
}
Python
def isPrime(n,i=2):
if(n<=1):
return False
elif(i==n):
return True
elif(n%i==0):
return False
else:
return isPrime(n,i+1)
#Main Method Starts from here
if(__name__=='__main__'):
number=int(input("Enter a number:"))
if(isPrime(number) == True):
print(number,"IS A PRIME NUMBER")
else:
print(number, "IS NOT A PRIME NUMBER")