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.

Example

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)

Output

Enter the number that you wish to examine : 46
The number is being checked…
The number is not a prime number

Explanation

  • 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.

Updated on: 12-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements