B.Sc Computer Science with Data Analytics
Python Programming - Lab
Core Lab 5
Bharathiar University
Program 8 - Write recursive functions to display prime number from 2 to n.
SOURCE CODE:
def is_prime(num, divisor=2):
if num <= 2:
return num == 2
if num % divisor == 0:
return False
if divisor * divisor > num:
return True
return is_prime(num, divisor + 1)
def display_primes(n, current=2):
if current <= n:
if is_prime(current):
print(current, end=" ")
display_primes(n, current + 1)
# read n value from user
num = int(input("Enter a number (n) to display prime numbers from 2 to n: "))
# Check if the input is non-negative
if num < 2:
print("Prime numbers start from 2. Please enter a number greater than or equal to 2.")
else:
print("Prime numbers from 2 to", num, "are:")
display_primes(num)
OUTPUT
Enter a number (n) to display prime numbers from 2 to n: 10
Prime numbers from 2 to 10 are:
2 3 5 7
No comments:
Post a Comment