Find Prime numbers in a range
PROBLEM :
Generate all prime numbers between two given numbers.
Input:
The first line of the input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of a single line containing two space separated integers m and n.
Output:
For every test case print all prime numbers p such that m <= p <= n, space separated. Separate the answers for each test case by a new line.
Constraints:
1<=T<=60
1 <= m <= n <= 100000,
n - m <= 100000
Example:
Input:
2
1 10
3 5
Output:
2 3 5 7
3 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void Prime_numbers_range(int ,int ) ;
int main()
{
int t,n1,n2 ;
cin>>t ;
while(t--)
{
cin>>n1>>n2 ;
Prime_numbers_range(n1,n2) ;
cout<<endl ;
}
return 0;
}
void Prime_numbers_range(int n1,int n2)
{
int arr[n2] ;
int i,j ;
arr[0]=0 ;
arr[1]=0 ;
for(i=2;i<=n2;i++)
arr[i]=1 ;
for(i=2;i<=n2;i++)
{
if(arr[i]==1)
{
for(j=i+1;j<=n2;j++)
if(j%i==0)
arr[j]=0 ;
}
}
for(i=n1;i<=n2;i++)
if(arr[i]==1)
cout<<i<<" " ;
}
---------------------------------------------------------------------------------
Generate all prime numbers between two given numbers.
Input:
The first line of the input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of a single line containing two space separated integers m and n.
Output:
For every test case print all prime numbers p such that m <= p <= n, space separated. Separate the answers for each test case by a new line.
Constraints:
1<=T<=60
1 <= m <= n <= 100000,
n - m <= 100000
Example:
Input:
2
1 10
3 5
Output:
2 3 5 7
3 5
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
#include<iostream>
using namespace std;
void Prime_numbers_range(int ,int ) ;
int main()
{
int t,n1,n2 ;
cin>>t ;
while(t--)
{
cin>>n1>>n2 ;
Prime_numbers_range(n1,n2) ;
cout<<endl ;
}
return 0;
}
void Prime_numbers_range(int n1,int n2)
{
int arr[n2] ;
int i,j ;
arr[0]=0 ;
arr[1]=0 ;
for(i=2;i<=n2;i++)
arr[i]=1 ;
for(i=2;i<=n2;i++)
{
if(arr[i]==1)
{
for(j=i+1;j<=n2;j++)
if(j%i==0)
arr[j]=0 ;
}
}
for(i=n1;i<=n2;i++)
if(arr[i]==1)
cout<<i<<" " ;
}
---------------------------------------------------------------------------------
Comments
Post a Comment