AtCoder Beginner Contest 084 D - 2017-like Number【数论/素数/前缀和】

D - 2017-like Number


Time limit : 2sec / Memory limit : 256MB

Score : 400 points

Problem Statement

We say that a odd number N is similar to 2017 when both N and (N+1)⁄2 are prime.

You are given Q queries.

In the i-th query, given two odd numbers li and ri, find the number of odd numbers x similar to 2017 such that lixri.

Constraints

  • 1≤Q≤105
  • 1≤liri≤105
  • li and ri are odd.
  • All input values are integers.

Input

Input is given from Standard Input in the following format:

Q
l1 r1
:
lQ rQ

Output

Print Q lines. The i-th line (1≤iQ) should contain the response to the i-th query.


Sample Input 1

Copy
1
3 7

Sample Output 1

Copy
2
  • 3 is similar to 2017, since both 3 and (3+1)⁄2=2 are prime.
  • 5 is similar to 2017, since both 5 and (5+1)⁄2=3 are prime.
  • 7 is not similar to 2017, since (7+1)⁄2=4 is not prime, although 7 is prime.

Thus, the response to the first query should be 2.


Sample Input 2

Copy
4
13 13
7 11
7 11
2017 2017

Sample Output 2

Copy
1
0
0
1

Note that 2017 is also similar to 2017.


Sample Input 3

Copy
6
1 53
13 91
37 55
19 51
73 91
13 49

Sample Output 3

Copy
4
4
1
1
1
2
【题意】:当N和(N + 1)/ 2都是素数时,奇数N与2017相似。 你有Q个查询。 在第i个查询中,给定两个奇数Li和Ri,找到与2017相似的奇数x的数目,使得li≤x≤ri。
【分析】:筛素数用埃筛,查询用前缀和。
【代码】:
#include<bits/stdc++.h>
using namespace std;
bool f [100001];
int c [100002];
int N,L,R ;
int main ()
{
    for (int i =2; i<=100000; i++)
        if (!f[i])
        for (int j = i+i ;j<=100000; j+=i )
                f[j]= true ;

    for (int i =3; i<=100000; i+=2)
        if (!f[i] && !f[(i+1)/2])
            c[i]++;

    for (int i =3; i <=100000; i ++)
            c[i]+=c[i-1];

    scanf ("%d",&N);
    while (N--)
    {
        scanf ("%d%d" ,&L ,&R );
        printf ("%d\n" , c[R] - c[L-1]);
    }
}
前缀和

 

posted @ 2017-12-31 12:13  Roni_i  阅读(259)  评论(0)    收藏  举报