Composites and Primes Sieve of Eratosthenes dp
/*
Given two integers L and R find the difference of number of composites and primes between the range L and R (both inclusive).
Input:
First line of input contains of an integer 'T' denoting number of test cases . Then T test cases follow.
Each test contains two integers L and R .
Output:
For each case print an integer corresponding to the answer .
Constraints:
1<=T<=100
1<=L<=R<=10^7
Example:
Input:
2
4 4
4 6
Output:
1
1
*/
// given l , r print no of comp- no of prime T.C->0.21
// normal approac i*i<=n gives TLE > 3.14
#include<bits/stdc++.h>
using namespace std;
bool prime[100001];
void SieveOfEratosthenes()
{
memset(prime, true, sizeof(prime));
prime[0]=false;
prime[1]=false;
for (int p=2; p*p<=10000000; p++)
{
if (prime[p] == true) // we make all multiples of prime false
{
for (int i=p*p; i<=10000000; i += p) // we make all multiples of prime false
prime[i] = false;
}
}
}
bool checkPrime(int num){
return prime[num];
}
int main() {
//code
SieveOfEratosthenes();
int t;
cin>>t;
while(t--){
int l,r;
cin>>l>>r;
int cn=0,pn=0;
for(int i=l;i<=r;i++){
if(checkPrime(i) && i>1){
pn++;
}else{
if(i>1){
cn++;
}
}
}
cout<<(cn-pn)<<endl;
}
return 0;
}
Given two integers L and R find the difference of number of composites and primes between the range L and R (both inclusive).
Input:
First line of input contains of an integer 'T' denoting number of test cases . Then T test cases follow.
Each test contains two integers L and R .
Output:
For each case print an integer corresponding to the answer .
Constraints:
1<=T<=100
1<=L<=R<=10^7
Example:
Input:
2
4 4
4 6
Output:
1
1
*/
// given l , r print no of comp- no of prime T.C->0.21
// normal approac i*i<=n gives TLE > 3.14
#include<bits/stdc++.h>
using namespace std;
bool prime[100001];
void SieveOfEratosthenes()
{
memset(prime, true, sizeof(prime));
prime[0]=false;
prime[1]=false;
for (int p=2; p*p<=10000000; p++)
{
if (prime[p] == true) // we make all multiples of prime false
{
for (int i=p*p; i<=10000000; i += p) // we make all multiples of prime false
prime[i] = false;
}
}
}
bool checkPrime(int num){
return prime[num];
}
int main() {
//code
SieveOfEratosthenes();
int t;
cin>>t;
while(t--){
int l,r;
cin>>l>>r;
int cn=0,pn=0;
for(int i=l;i<=r;i++){
if(checkPrime(i) && i>1){
pn++;
}else{
if(i>1){
cn++;
}
}
}
cout<<(cn-pn)<<endl;
}
return 0;
}
Comments
Post a Comment