TechoSagar: Sieve of Eratosthenes

Sieve of Eratosthenes

Given a number n, calculate the prime numbers upto n using Sieve of Eratosthenes.  
Input: The first line of the input contains T denoting the number of testcases. First line of test case is the number to which we have to compute prime numbers.
Output: All the prime numbers upto or equal to n are displayed.
Constraints:
1 <=T<= 100
1 <=N<= 10000
Example:
Input:
2
10
35
Output:
2 3 5 7
2 3 5 7 11 13 17 19 23 29 31 
Your Code
#include<iostream>

using namespace std;
 void prime(int);
int main()
{
int t,x,i, temp=1;
cin>>t;
while(t--)
{
int n;
cin>>n;
if(n!=1)
{
for(x=2; x<=n; x++) 
{   
 prime(x);
}
}
cout<<endl;
}
return 0;
}

void prime(int n)
{ int i, temp=1;


 for(i=2; i<=n/2; i++)
  {
  if(n%i==0)
  {
  temp=0;
  break;
    }
 }  

if(i!=1)
{


  if(temp==1)
  {
   cout<<n<<" ";
  
  }
}
}

Follow us

Follow Bijendra Kumar on Facebook