Python Program to Print Prime Numbers of a Given Interval.

Given two integer values 'start' and 'end' as an interval. Write a Python program to print all prime numbers present in this interval.

Prime numbers are positive integers greater than 1 that have no positive integer divisors other than 1 and themselves. To find prime numbers in a given interval, we need to check each number in the interval whether it is a prime number or not. Example: 2, 3, 5, 7, 11, etc. (alert-success)


Python Program to find Prime numbers in the given Interval.

# Function to check if a number is prime
def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

# Function to find prime numbers in a given interval
def find_primes(start, end):
    prime_numbers = []
    for num in range(start, end+1):
        if is_prime(num):
            prime_numbers.append(num)
    return prime_numbers

# Example usage
start = 10
end = 50
print("Prime numbers between", start, "and", end, "are:")
print(find_primes(start, end))
Output:
Prime numbers between 10 and 50 are:
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Explanation:
In the above program, to check if a number is a prime, we use a for loop that iterates from 2 to the square root of the number. If the number is divisible by any number in this range, it is not a prime number. Otherwise, it is a prime number.
  • Time Complexity: The overall time complexity is O(n*sqrt(n)) where n is the difference start and end interval. 
  • Space Complexity: The overall space complexity is O(n) because we are creating a list of prime numbers which can have a maximum size of n.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS