Python Program - Print all Prime Numbers in an Interval
Here's a Python program to print all prime numbers in an interval:
rei:ot refgiftidea.com# function to check if a number is prime or not def is_prime(n): # check if n is 2, the only even prime number if n == 2: return True # check if n is even or less than 2 if n % 2 == 0 or n < 2: return False # check if n is divisible by any odd number less than n for i in range(3, int(n ** 0.5) + 1, 2): if n % i == 0: return False return True # take input from user lower = int(input("Enter lower limit of the interval: ")) upper = int(input("Enter upper limit of the interval: ")) # print all prime numbers in the interval print(f"Prime numbers between {lower} and {upper} are:") for num in range(lower, upper + 1): if is_prime(num): print(num)
In this program, we first define a function is_prime(n)
that takes a number n
as input and returns True
if it is prime, and False
otherwise. We use the fact that a number is prime if it is not divisible by any number except 1 and itself. We first check if n
is 2, the only even prime number. If not, we check if n
is even or less than 2, in which case it is not prime. Otherwise, we check if n
is divisible by any odd number less than n
using a loop that starts from 3 and goes up to the square root of n
, checking only odd numbers.
Then, we take input from the user for the lower and upper limits of the interval, and use a loop to iterate over all numbers in the interval. For each number, we call the is_prime()
function to check if it is prime, and print it if it is.