Getting all prime numbers from 2 to some points of number(Sieve of Eratosthenes)
We are interested in getting all the prime numbers from 2 to any number.
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<”Enter the value of n:”;
cin>>n;
if(n>=2)
{
int A[n+1];
for(int i=0;i<=n;i++){ //We can change the condition i*i<n as to optimise
A[i]=1;
}
for(int i=2;i<n+1;i++){
if(A[i]){
int k=2;
int a=i*k;
while(a<(n+1)){
A[a]=0;
k++;
a=i*k;
}
}
}
cout<<”{“;
for(int i=2;i<=n;i++){
if(A[i]){
cout<<i<<”,”;
}
}
cout<<”\b”;
cout<<”}”;
}
else{
cout<<”No prime number exist”;
}
}