Python Program to Print all Prime Numbers in an Interval

In this program, you’ll learn to print all prime numbers within an interval using different methods.

In mathematics, a prime number is a positive integer greater than 1 that can only be evenly divided by 1 and itself.
This means that a prime number has no other positive integer divisors besides 1 and itself.
The property of being prime is called primality and there are infinitely many primes

For instance, the first few prime numbers are 2, 3, 5, 7, 11, 13, and so on. These numbers are unique because they cannot be divided by any other number except for 1 and themselves.

Prime numbers have significant implications in many fields, including number theory, cryptography, and computer science. In fact, they play a vital role in securing online transactions through public key cryptography algorithms, as well as ensuring the integrity of data through hashing functions.

Using a for loop to print a range of prime numbers in interval

# program to print prime numbers in a range

# define the range
start = 1
end = 100

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)

Output

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

In the above program, we define the range of numbers to check for prime numbers. We use a for loop to iterate over a number in the range and check whether it is prime or not.
Again in the inner block, we use a nested for loop to check if the number is divisible by any number other than 1 and itself. If a number is not divisible by any number other than 1 and itself, we print the number.

Using a while loop

# program to print a limited number of prime numbers

# define the limit
limit = 25

print("The first", limit, "prime numbers are:")

# initialize variables
num = 2
count = 0

# loop until we have found enough prime numbers
while count < limit:
    # check if num is prime
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            break
    else:
        print(num)
        count += 1
    num += 1

Output

The first 25 prime numbers 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

In the above program, we use a while loop to iterate over each number until we have found enough prime numbers.
To check if a number is a prime, we use an inner for loop to check if it is divisible by any number other than 1 and itself. If the number is not divisible by any number other than 1 and itself, we print the number as a prime number and increment the counter.

Leave a Comment