Advertisement
AquaBlitz11

Sieve of Eratosthenes

Oct 19th, 2016
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.83 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6.     int n;
  7.     cin >> n;
  8.    
  9.     bool cut[n + 1]; // list of number from 1 to n that has been discarded (ignore 0 and 1)
  10.     for (int i = 0; i <= n; i++) // initialize false
  11.         cut[i] = false;
  12.  
  13.     // keep cutting
  14.     int curMin = 2;
  15.     while (curMin <= n)
  16.     {
  17.         // starts cutting from second multiple of it
  18.         // for example, curMin = 2 will cut 4, 6, 8, 10, ...
  19.         for (int i = 2 * curMin; i <= n; i += curMin)
  20.             cut[i] = true;
  21.        
  22.         // finds next not-yet-cut number (prime number)
  23.         do
  24.         {
  25.             curMin++;
  26.         } while (cut[curMin]);
  27.     }
  28.    
  29.     // print all non-cut number
  30.     for (int i = 2; i <= n; i++)
  31.     {
  32.         if (!cut[i])
  33.             cout << i << endl;
  34.     }
  35.  
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement