Home » Prime Number Using Recursion in Python

Prime Number Using Recursion in Python

Learn about Prime Number Using Recursion in Python in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.

A Prime Number is a positive integer greater than 1 which is divisible by 1 and itself.

Prime Number Using Recursion in Python

In the below program the function isPrime() recursively checks whether the given number is a prime or not. If the given number is a prime number then it returns True else False.

Program:

# Python program to check if a number is prime or not using recursion
# recursive function
def isPrime(num, i = 2):  
    if (num <= 2): 
        return True if(num == 2) else False
    if (num % i == 0): 
        return False
    if (i * i > num): 
        return True

    # Check next divisor 
    return isPrime(num, i + 1)
  
# input number
num = int(input('Enter a number: '))

# function call
if(isPrime(num)):
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")

Ouput:

Enter a number: 3
3 is a prime number

Hope the above code works for you and Refer to the below Related Codes to gain more insights. Happy coding and come back again.

Similar Code : Prime Number in Python using Function