Created
December 12, 2021 09:32
-
-
Save ShawonAshraf/2942fefc692b5a4432c24da56fc84ab8 to your computer and use it in GitHub Desktop.
sieve prime example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import argparse | |
argument_parser = argparse.ArgumentParser() | |
argument_parser.add_argument("--n", type=int, required=True) | |
args = argument_parser.parse_args() | |
def is_prime(n): | |
if n == 1: | |
return False | |
for i in range(2, int(math.sqrt(n)) + 1): | |
if n % i == 0: | |
return False | |
return True | |
# excluding n | |
def primes_upto(n): | |
marked = [True] * (n - 1) | |
marked[0] = False | |
marked[1] = False | |
# print(marked) | |
for i in range(2, n): | |
status = is_prime(i) | |
if status: | |
print(f"Marking composites for {i}......") | |
for j in range(i + 1, len(marked)): | |
# if it's a multiple | |
if j % i == 0: | |
marked[j] = False | |
# find the primes | |
primes = [] | |
for i in range(len(marked)): | |
if marked[i]: | |
primes.append(i) | |
# return | |
return primes | |
if __name__ == "__main__": | |
primes = primes_upto(args.n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment