[Luogu] P1865 A % B Problem

题目描述

区间质数个数

输入输出格式

输入格式:

一行两个整数 询问次数n,范围m

接下来n行,每行两个整数 l,r 表示区间

输出格式:

对于每次询问输出个数 t,如l或r∉[1,m]输出 Crossing the line

题目解析

素数筛 + 前缀和,筛的过程中处理前缀和,感觉很有趣的思路。

Code

#include<iostream>
#include<cstdio>
using namespace std;

const int MAXN = 1000 + 5;
const int MAXM = 1000000 + 5;

int n,m,l,r;
int a[MAXM],vis[MAXM];

inline int rd() {
    int x=0,f=1;char ch=getchar();
    while(!isdigit(ch)) {f=(ch=='-')?-1:1;ch=getchar();}
    while(isdigit(ch)) {x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

inline void find_prime() {
    a[1] = 0;
    vis[1] = true;
    for(int i = 2;i <= m;i++) {
        if(!vis[i]) {
            a[i] = a[i-1] + 1;
            for(int j = i+i;j <= m;j = j+i) vis[j]=true;
        } else a[i] = a[i-1];
    }
    return;
}

int main() {
    scanf("%d%d",&n,&m);
    find_prime();
    while(n--) {
        l = rd(), r = rd();
        if(l < 1 || m < r) {
            puts("Crossing the line");
            continue;
        }
        printf("%d
",a[r]-a[l-1]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/floatiy/p/9868724.html