题目要求
给定 ,求区间 内质数的个数。
解题思路
我们可以使用判素数和前缀和解决,判素数就是从 有没有 能整除。代码如下:
bool pss(int n){
if(n < 2) return 0;
for(int i=2;i*i<=n;++i){//循环枚举2~sqrt(n)
if(n % i == 0) return 0;
}
return 1;
}有了这个,我们就可以用前缀和统计 内所有质数啦! 代码如下:
for(int i=1;i<=m;++i){
a[i] = a[i-1]+pss(i);//前缀和
}最后我们在检查一下 有没有超出范围,就可以输出啦!
AC code:
#include<bits/stdc++.h>
using namespace std;
int a[1000005];
bool pss(int n){//循环枚举2~sqrt(n)
if(n < 2) return 0;
for(int i=2;i*i<=n;++i){
if(n % i == 0) return 0;
}
return 1;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int n,m;
cin>>n>>m;
for(int i=1;i<=m;++i){
a[i] = a[i-1]+pss(i);//前缀和
}
while(n--){
int l,r;
cin>>l>>r;
if(l >= 1 && r >= 1 && l <= m && r <= m){
cout<<a[r]-a[l-1]<<'\n';
}
else cout<<"Crossing the line\n";//有没有超出范围
}
return 0;
}