Skip to content

Commit 0b72ef4

Browse files
Sieve of Eratosthenes
Algorithm to obtain prime numbers from 1 to N. (Regarded as the oldest algorithm in the world)
1 parent 51866aa commit 0b72ef4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

sieve.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void SieveOfEratosthenes(int n)
5+
{
6+
// Create a boolean array and initialize the values as true
7+
bool prime[n+1];
8+
memset(prime, true, sizeof(prime));
9+
10+
for (int p=2; p*p<=n; p++)
11+
{
12+
// If prime[p] is not changed, then it is a prime
13+
if (prime[p] == true)
14+
{
15+
//Update multiples
16+
for (int i=p*p; i<=n; i += p)
17+
prime[i] = false;
18+
}
19+
}
20+
21+
// Print all prime numbers
22+
for (int p=2; p<=n; p++)
23+
if (prime[p])
24+
cout << p << " ";
25+
}
26+
27+
// Driver Program
28+
int main()
29+
{
30+
int n = 30;
31+
cout << " Prime Numbers in the range 1 to " << n << endl;
32+
SieveOfEratosthenes(n);
33+
return 0;
34+
}

0 commit comments

Comments
 (0)