This is a Python Program to find if a number is prime or not using recursion.
The program takes a number and finds if the number is prime or not using recursion.
1. Take a number from the user.
2. Pass the number as an argument to a recursive function and initialize the divisor count to NULL.
3. Then check the number of divisors of the number using recursion and either True or False is returned.
4. The final result is printed.
5. Exit.
Here is source code of the Python Program to find if a number is prime or not using recursion. The program output is also shown below.
def check(n, div = None): if div is None: div = n - 1 while div >= 2: if n % div == 0: print("Number not prime") return False else: return check(n, div-1) else: print("Number is prime") return 'True' n=int(input("Enter number: ")) check(n)
1. User must enter a number.
2. The number is passed as an argument to a recursive function and the divisor count is initialized to NULL.
3. The divisor is initialized to the number minus 1.
4. The number of divisors of the number is checked using recursion and either True or False is returned.
5. Final result is printed.
Case 1: Enter number: 13 Number is prime Case 2: Enter number: 30 Number not prime
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Practice Programming MCQs
- Check Python Books
- Apply for Programming Internship
- Check Information Technology Books
- Apply for Python Internship