Generate Prime numbers in Python

In this article, we cover how to generate a range of prime numbers in Python.

Introduction

A positive integer that has only two factors i.e. one and itself is a prime number. In other words, a prime number ‘n’ would have only two factors: 1 and n. These are different from composite numbers which have more than two factors.

It is worth mentioning here that, 1 is not a prime number as it has only one divisor. And, the numbers that are not prime are basically composite numbers.

Prime numbers are mainly used in cryptography.

Python program that helps generate Prime numbers

ran = int(input("Enter a range: "))
p_numbers = []
if ran >= 2:
    p_numbers.append(2)
for i in range(3,ran+1):
    for j in range(2,i):
       if i==j:
          continue
       elif i % j == 0:
          break
    else:
       p_numbers.append(i)
print(f"List of prime numbers till range: {ran}\n{p_numbers}")

Here, we have tried to generate a list of prime numbers till a range the user specifies. It gets stored in variable ran. If it finds a prime number within the given range then it stores the number in the list p_numbers.

2 is a prime number. So, we chose to append our p_numbers list with 2 for a given range that is greater than or equal to 2.

Thereafter, we used two for loops. As the range function doesn’t include the end value. So, we did ran + 1. And, inside the for loop, we used another for loop that checks if a number in the range is divisible by other numbers till that range.

Notice that, we have used for-else. If the number isn’t divisible by other numbers then it would append the number in the list p_numbers.

Lastly, we use print() to display the list of prime numbers.

Testing the Code

When we run our code, it prompts us to Enter a range: We can use 100 or any number of your choice.

Enter a range: 100

It would check for prime numbers in the given range in the background. And, when done, prints all the prime numbers that are in the specified range.

So, for prime numbers till the range 100, we got the following output:

List of prime numbers till range: 100
[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]

Conclusion

In this article, we covered how to generate all the prime numbers within a desired range. There are multiple ways to write the program. In the subsequent article, we cover how we can check whether a given number is a prime number or not.

More about Prime numbers:

1https://en.wikipedia.org/wiki/Prime_number

Similar Posts