Skip to content

Commit ff16d80

Browse files
Create Sieve of Eratosthenes.md
1 parent 22ba3f6 commit ff16d80

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2+
```py
3+
def sieve_of_eratosthenes(n):
4+
# Create a boolean array, initialized to True, indicating all numbers are prime
5+
is_prime = [True] * (n + 1)
6+
p = 2
7+
while (p * p <= n):
8+
# If is_prime[p] has not been marked as False, it is a prime number
9+
if is_prime[p]:
10+
# Mark all multiples of p as False, starting from p squared
11+
for i in range(p * p, n + 1, p):
12+
is_prime[i] = False
13+
p += 1
14+
15+
# Collect all numbers that have not been marked as False, which are prime
16+
primes = [p for p in range(2, n + 1) if is_prime[p]]
17+
return primes
18+
19+
# Test the algorithm to find all primes less than or equal to 100
20+
n = 100
21+
primes = sieve_of_eratosthenes(n)
22+
print(f"All primes less than or equal to {n}: {primes}")
23+
24+
```
25+
26+
27+

0 commit comments

Comments
 (0)