Header Ads

Learn Together, Stay Connected.

Sieve of Eratosthenes- C++

 #include<bits/stdc++.h>

using namespace std;

void sieve(long long n)
{
bool prime[n+1];
memset(prime,true,sizeof(prime));
long long i,p=0,j;
for(i=2;i*i<=n;i++)
{
if(prime[i])
{
for(j=i*i;j<=n;j+=i)
{
prime[j]=false;
}
}
}
for(i=2;i<=n;i++)
{
if(prime[i])
{
cout<<i<<" ";
p++;
}

}
cout<<endl<<p<<endl;

}



int main()
{
ios_base :: sync_with_stdio(0);cin.tie(0);cout.tie(0);
//freopen("input.txt","r",stdin);
long long n;
cin>>n;
sieve(n);
return 0;
}

No comments

Theme images by Dizzo. Powered by Blogger.