- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Find if a Number is Prime or Not Prime Using Recursion
When it is required to find out if a number is a prime number or not using recursion technique, a method is defined, and the ‘while’ condition is used.
The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.
Below is a demonstration for the same −
def check_prime(my_num, my_val = None): if my_val is None: my_val = my_num – 1 while my_val >= 2: if my_num % my_val == 0: print(“The number is not a prime number”) return False else: return check_prime(my_num, my_val-1) else: print(“The number is a prime number”) return ‘True’ my_num = int(input(“Enter the number that you wish to examine : “)) print(“The number is being checked…”) check_prime(my_num)
Enter the number that you wish to examine : 46 The number is being checked… The number is not a prime number
- A method named ‘check_prime’ is defined, that takes theand a value that is assigned to None as a parameter.
- If the variable is None, the variable is assigned to the number decremented by 1.
- If the value of the variable is greater than 2, the number is divided by the value, and its remainder is compared to 0.
- If the remainder is 0, it is considered as a non-prime number.
- Otherwise, the method is called again by passing the number, and the value decremented by 1.
- Outside the function, the user is asked to enter a number that needs to be checked.
- The number is checked, by calling the function and passing this value as a parameter.
- The relevant output is displayed on the console.
- Python program to check if a number is Prime or not
- C# Program to check if a number is prime or not
- PHP program to check if a number is prime or not
- Bash program to check if the Number is a Prime or not
- Check if a number is Primorial Prime or not in Python
- 8085 program to determine if the number is prime or not
- Write a C# program to check if a number is prime or not
- How to check whether a number is prime or not using Python?
- Check if a number is Quartan Prime or not in C++
- Check if a number is Primorial Prime or not in C++
- C++ Program to Check Whether a Number is Prime or Not
- C Program to Check Whether a Number is Prime or not?
- Java Program to Check Whether a Number is Prime or Not
- Check if a number is a Pythagorean Prime or not in C++
- Prime or not in Python