WUT_Computer_Science/code/project.py

47 lines
1.4 KiB
Python
Raw Normal View History

2022-11-08 20:40:43 +01:00
'''Python program to print all Primes Smaller than or equal to N using Sieve of Eratosthenes'''
import time
import math
2022-11-08 20:40:43 +01:00
def sieve_of_eratosthenes(num: int) -> list[int]:
"""Finds all prime number from 1 to num.
Args:
num (int): Number up to which the prime numbers should be printed
Returns:
list[int]: List of prime numbers
"""
2022-11-25 23:56:20 +01:00
# boolean list to store if a number is prime or not
2022-11-08 20:40:43 +01:00
prime = [True] * (num+1)
2022-11-25 23:56:20 +01:00
p = 2 # starting prime number
# we will iterate till square root of num because
# if a number is not prime then it will have a factor less than or equal to square root of that number
2022-11-08 20:40:43 +01:00
while p <= math.sqrt(num):
# If prime[p] is not
# changed, then it is a prime
2022-11-08 20:40:43 +01:00
if prime[p]:
2022-11-25 23:56:20 +01:00
i = (p << 1) # i = p * 2
# Updating all multiples of p
2022-11-08 20:40:43 +01:00
while i <= num:
prime[i] = False
2022-11-08 20:40:43 +01:00
i += p
p += 1
2022-11-08 20:40:43 +01:00
return [p for p in range(2, num+1) if prime[p]]
def print_sieve(num: int) -> None:
"""Prints all prime number from 1 to num.
Args:
num (int): Number up to which the prime numbers should be printed
"""
for number in sieve_of_eratosthenes(num):
print(number, end=" ")
# Driver code
if __name__ == '__main__':
2022-11-08 20:40:43 +01:00
num = 3000
print("Following are the prime numbers smaller"),
print("than or equal to", num)
2022-11-08 20:40:43 +01:00
print_sieve(num)