P1865 A % B Problem (prefix and plus prime number sieve)

topic background

The title of the topic is what attracts you to click

In fact, the question is still very watery

Topic description

interval prime numbers

Input and output format

Input format:

 

Two integer query times n in one line, range m

Next n lines, each line two integers l, r represent the interval

 

Output format:

 

For each query output number t, such as l or r∉[1,m] output Crossing the line

 

Input and output example

Input Example #1:  Copy

2 5
1 3
2 6

Output Sample #1:  Copy

2
Crossing the line

illustrate

【Data Scope and Convention】

For 20% of the data 1<=n<=10 1<=m<=10

对于100%的数据 1<=n<=1000 1<=m<=1000000 -10^9<=l<=r<=10^9 1<=t<=1000000

 


Ideas:

Using the Angstrom sieve method, combine the prefix sums.

Although the data range is very large, in fact, one-dimensional arrays can also be opened to 1e9. Note that we should not use the table to find all the prime numbers in the range, otherwise it will definitely time out.

 


Code:

#include<iostream> 
using namespace std;
int n,m;
int l,r;
int prime[100000005];
int f[100000005];//存前缀和,f数组存的是2~i的范围内素数的个数 

void isprime()
{
	prime[0]=prime[1]=true; //不是素数 
	for(int i=2;i*i<=m;i++)
	{
		if(!prime[i])
		{
			for(int j=i*i;j<=m;j+=i)
				prime[j]=true;
		}
	}
	//求前缀和	
	for(int i=2;i<=m;i++) //范围是2到m 
	{
		f[i]=f[i-1];  
		if(!prime[i]) //如果是素数,f的值加一 
			f[i]++;	
	}	
} 

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>n>>m;
	isprime();
	while(n--)
	{
		cin>>l>>r;
		if(l<=0 || r>m) //不符合范围 
		{
			cout<<"Crossing the line"<<endl;
			continue;	
		}	
		cout<<f[r]-f[l-1]<<endl; //一定要注意 l-1 
	}
	return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326312965&siteId=291194637