1. Introduction
Finding prime numbers within a specified range is a classic problem in computer science and mathematics. Prime numbers are numbers greater than 1 that have no positive divisors other than 1 and themselves. Python provides a straightforward way to implement this using loops and conditional logic.
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In other words, it has exactly two distinct positive divisors: 1 and the number itself.
2. Program Steps
1. Define the range within which to find prime numbers.
2. Iterate over this range using a loop.
3. For each number, check if it is prime by trying to divide it by all smaller numbers except 1.
4. If a number is only divisible by itself and 1, consider it prime and store or print it.
5. Continue this process for the entire range.
3. Code Program
# 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 print prime numbers in a range
def print_primes_in_range(start, end):
for number in range(start, end + 1):
if is_prime(number):
print(number)
# Define the range
start_range = 10
end_range = 50
# Call the function to print prime numbers in the range
print_primes_in_range(start_range, end_range)
Output:
11 13 17 19 23 29 31 37 41 43 47
Explanation:
1. is_prime is a helper function that takes an integer num and returns True if the number is prime.
2. Inside is_prime, any number less than or equal to 1 is immediately not prime.
3. The function uses a for loop to iterate from 2 to the square root of num (an optimized check for divisors).
4. If num is divisible by any number in this range (checked using num % i == 0), it is not prime.
5. print_primes_in_range is the main function that prints all prime numbers in a specified range from start to end.
6. It loops through each number in the range and calls is_prime to check if the number is prime.
7. If is_prime returns True, the number is printed.
8. When print_primes_in_range is called with the range 10 to 50, it prints all the prime numbers within that range.
Comments
Post a Comment
Leave Comment