How to Create Sieve of Eratosthenes in Python
In this tutorial, we’ll learn how to program "How to Create Sieve of Eratosthenes in Python". The objective is to understand and implement a method for efficiently identifying prime numbers using the Sieve of Eratosthenes algorithm. This tutorial will guide you step by step through the process, ensuring a clear understanding of how to create and apply this powerful algorithm. So, let’s get started!
This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will show you the proper way to create the Sieve of Eratosthenes. So, let’s dive into the coding process!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- def SieveOfEratosthenes(num):
- prime = [True for i in range(num+1)]
- p = 2
- while (p * p <= num):
- if (prime[p] == True):
- for i in range(p * p, num+1, p):
- prime[i] = False
- p += 1
- for p in range(2, num+1):
- if prime[p]:
- print(p)
- if __name__ == '__main__':
- while True:
- print("\n================= Sieve of Eratosthenes =================\n\n")
- num = int(input("Enter a number: "))
- print("Following are the prime numbers smaller"),
- print("\nthan or equal to", num)
- SieveOfEratosthenes(num)
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- continue
This program implements the Sieve of Eratosthenes algorithm to find all prime numbers less than or equal to a user-provided number. It begins by initializing a list to track prime numbers, iteratively marks multiples of each prime as non-prime, and then outputs all the remaining prime numbers. The user can choose to run the program again with a new input or exit after each execution.
Output:
There you have it we successfully created How to Create Sieve of Eratosthenes in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language
Add new comment
- 17 views