Skip to content

Commit 0bf6cf2

Browse files
authored
Merge pull request #234 from the-hdr/main
Add sieve_of_eratosthenes.cpp
2 parents 328dadb + a0e1ce8 commit 0bf6cf2

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Coding/sieve_of_eratosthenes.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
void sieve (vector<bool>& isPrime)
7+
{
8+
int upperLimit = isPrime.size() - 1;
9+
10+
isPrime[0] = isPrime[1] = false;
11+
for (int i = 2; i*i <= upperLimit; ++i)
12+
{
13+
if (isPrime[i])
14+
{
15+
for (int j = i*i; j <= upperLimit; j += i)
16+
{
17+
isPrime[j] = false;
18+
}
19+
}
20+
}
21+
}
22+
23+
int main()
24+
{
25+
cout << "Enter the number till which you want to know all the primes: ";
26+
int userInput;
27+
cin >> userInput;
28+
29+
vector<bool> isPrime (userInput + 1, true);
30+
sieve (isPrime);
31+
32+
cout << "All the primes till " << userInput << ": " << endl;
33+
for (int currentNumber = 2; currentNumber <= userInput; ++currentNumber)
34+
{
35+
if (isPrime[currentNumber])
36+
{
37+
cout << currentNumber << ' ';
38+
}
39+
}
40+
cout << endl;
41+
42+
return 0;
43+
}

0 commit comments

Comments
 (0)