Guest User

Prime sieve

a guest
May 20th, 2021
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. #include"bits/stdc++.h"
  2. using namespace std;
  3. int MAXN=1000000;
  4. void sieve(int *p)
  5. {
  6.     // firstly mark all odd numbers as primes
  7.     // as we will have all primes except 2 as odd
  8.     for(int i=3;i<=MAXN;i+=2)
  9.         p[i]=1;
  10.     p[1]=p[0]=0;
  11.     p[2]=1; // 2 is the only even prime
  12.  
  13.     // sieve
  14.     for(int i=3;i*i<=MAXN;i+=2)
  15.     {
  16.         if(p[i]==1) // marking all multiples of p[i] as not prime
  17.         {
  18.             for(int j=i*i;j<=MAXN;j+=i)
  19.                 p[j]=0;
  20.         }
  21.     }
  22. }
  23.  
  24. int main()
  25. {
  26.     int primes[MAXN]={0};
  27.     cout<<"Enter value for n:\n";
  28.     int n;
  29.     cin>>n;
  30.     sieve(primes);
  31.     for(int i=0;i<=n;i++)
  32.         if(primes[i]==1)
  33.             cout<<i<<" ";
  34.  
  35.     return 0;
  36.  
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment