forked from iam-abbas/cs-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million or so
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# Python program to print all primes smaller than or equal to | ||
# n using Sieve of Eratosthenes | ||
|
||
def SieveOfEratosthenes(n): | ||
|
||
# Create a boolean array "prime[0..n]" and initialize | ||
# all entries it as true. A value in prime[i] will | ||
# finally be false if i is Not a prime, else true. | ||
prime = [True for i in range(n+1)] | ||
p = 2 | ||
while (p * p <= n): | ||
|
||
# If prime[p] is not changed, then it is a prime | ||
if (prime[p] == True): | ||
|
||
# Update all multiples of p | ||
for i in range(p * p, n+1, p): | ||
prime[i] = False | ||
p += 1 | ||
|
||
# Print all prime numbers | ||
for p in range(2, n): | ||
if prime[p]: | ||
print p, | ||
|
||
# driver program | ||
if __name__=='__main__': | ||
n = 30 | ||
print "Following are the prime numbers smaller", | ||
print "than or equal to", n | ||
SieveOfEratosthenes(n) |