Python Program to Print all Prime Numbers in an Interval
A prime number is a positive integer greater than 1 that has exactly two factors, 1 and itself. In other words, a prime number cannot be evenly divided by any other number except 1 and itself. For example, the first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and so on.
Prime numbers have fascinated mathematicians for centuries because of their unique properties and their role in number theory. They are important in fields such as cryptography, where they are used to encrypt messages and secure online transactions. Prime numbers also have many applications in computer science, such as in the design of efficient algorithms for prime factorization, which is the process of finding the prime factors of a composite number.
Python Code :
The below Python program prints all prime numbers within a given interval:
# Get input interval from user start = int(input("Enter the start of the interval: ")) end = int(input("Enter the end of the interval: ")) # Check prime numbers in the interval print("Prime numbers between", start, "and", end, "are:") for num in range(start, end + 1): if num > 1: for i in range(2, num): if num % i == 0: break else: print(num)
In this program, the user is prompted to enter the start and end of the interval. The program then uses a for loop to iterate through all numbers in the interval from start to end using the expression for num in range(start, end + 1).
For each value of num, the program checks whether the number is a prime number using the same logic as the previous program. If num is a prime number, the program prints it out using the print statement inside the else block.
Note that this program assumes that the user enters valid integers for the start and end of the interval. If the user enters invalid input, such as a string or a non-numeric value, the program will raise a ValueError or produce an incorrect result.
For example :
Enter the start of the interval: 1 Enter the end of the interval: 100 Prime numbers between 1 and 100 are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97