File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Math/Sieve of Eratosthenes/C++ Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ // C++ program to print all primes smaller than or equal to
2
+ // n using Sieve of Eratosthenes in O(n*log(log(n)))
3
+
4
+ #include < iostream>
5
+ #include < vector>
6
+ using namespace std ;
7
+
8
+ vector < bool > prime; // vector of bool to store whether number is prime or not.
9
+ void sieve (int n)
10
+ {
11
+ prime.resize (n + 1 ); // re-sizing the vector to required size
12
+
13
+ for (int j = 0 ; j <= n; j++)
14
+ prime[j] = true ; // Initially we consider all numbers to be prime and then sieve them out
15
+ // prime[x] is true implies x is a prime number
16
+
17
+ for (int p=2 ; p*p<=n; p++)
18
+ {
19
+ // If prime[p] is not changed, then it is a prime
20
+ if (prime[p] == true )
21
+ {
22
+ // Update all multiples of p greater than or
23
+ // equal to the square of it
24
+ // numbers which are multiple of p and are
25
+ // less than p^2 are already been marked.
26
+ for (int i=p*p; i<=n; i += p)
27
+ prime[i] = false ;
28
+ }
29
+ }
30
+ }
31
+
32
+ // Program to test the algorithm
33
+ int main ()
34
+ {
35
+ int n = 100 ;
36
+ sieve (n);
37
+ cout << " Following are the prime numbers smaller than or equal to " << n << endl;
38
+ for (int j = 2 ; j <= n; j++)
39
+ if (prime[j])
40
+ cout << j << endl;
41
+ return 0 ;
42
+ }
You can’t perform that action at this time.
0 commit comments