File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments