1. Introduction
In this tutorial, we will learn how to write a Python program to check a number is a prime number using recursion.
Checking for prime numbers is a common operation in programming. A prime number is an integer greater than 1 that is not the product of two smaller positive integers. The recursive approach to check for a prime number involves dividing the number by each smaller integer greater than 1 to see if it can be divided without a remainder.
2. Program Steps
1. Define a function that uses recursion to check for a prime number.
2. If the number is less than 2, it's not prime.
3. Recursively check if the number can be divided by any other integer without a remainder.
4. If a divisor is found, the number is not prime.
5. If no divisors are found, the number is prime.
3. Code Program
# Function to check if a number is prime using recursion
def is_prime(number, divisor=None):
# If divisor is not set, initialize it to number - 1
if divisor is None:
divisor = number - 1
# Base case: if divisor is 1, then number is prime
if divisor == 1:
return True
# If number is divisible by divisor, it's not prime
if number % divisor == 0:
return False
# Recurse with the next smaller divisor
return is_prime(number, divisor-1)
# Number to be checked
num_to_check = 29
# Check if the number is prime and print the result
if is_prime(num_to_check):
print(f"{num_to_check} is a prime number.")
else:
print(f"{num_to_check} is not a prime number.")
Output:
29 is a prime number.
Explanation:
1. is_prime is a function that accepts number and an optional parameter divisor. It returns True or False to indicate if number is prime.
2. If divisor is not provided, it's initialized to number - 1, as we don't need to check divisibility by the number itself.
3. The base case occurs when divisor reaches 1. If this happens without finding any divisors, the number is prime.
4. The function checks if number is divisible by divisor (number % divisor == 0). If so, the number is not prime.
5. If not, the function calls itself (is_prime(number, divisor-1)), decrementing divisor by 1 to check the next potential divisor.
6. When is_prime(num_to_check) is called with num_to_check set to 29, the output confirms that 29 is a prime number as no divisors were found.
Comments
Post a Comment
Leave Comment