SPOJ FRQPRIME - Frequent Prime Ranges 二分

题目链接http://www.spoj.com/problems/FRQPRIME/

题目大意:询问[2,N]区间内的包含素数个数至少为K的区间的个数。

解题思路:素数个数前缀和+二分。哪儿位大侠有好方法的话希望在评论区说明。

代码:

 1 const int inf = 0x3f3f3f3f;
 2 const int maxn = 1e6 + 5;
 3 int sum[maxn];
 4 bool vis[maxn];
 5 int n, k;
 6 
 7 void dowork(){
 8     memset(vis, 0, sizeof(vis));
 9     memset(sum, 0, sizeof(sum));
10     for(int i = 2; i < maxn; i++)
11         for(int j = i + i; j > 0 && j < maxn; j += i)
12             vis[j] = 1;
13     for(int i = 2; i < maxn; i++)
14         if(!vis[i]) sum[i] = sum[i - 1] + 1;
15         else sum[i] = sum[i - 1];
16     
17 }
18 void solve(){
19     if(k == 0){
20         ll u = n;
21         ll ans = u * (u - 1) / 2;
22         printf("%lld\n", ans);
23         return;
24     }
25     ll ans = 0;
26     for(int i = 2; i <= n; i++){
27         int u = sum[i - 1] + k;
28         int v = lower_bound(sum, sum + n + 1, u) - sum;
29         ll x = n - v + 1;
30         ans += x;
31     }
32     printf("%lld\n", ans);
33 }
34 int main(){
35     dowork();
36     int t;
37     scanf("%d", &t);
38     while(t--){
39         scanf("%d %d", &n, &k);
40         solve();
41     }
42 }

题目:

FRQPRIME - Frequent Prime Ranges

 

A range [L..H] is called a K-Frequent Prime range if there are atleast K primes amongst the numbers L,L+1,..,H. Given N and K, calculate how many subranges of the range [2..N] are K-Frequent Prime.

Input

The first line contains the number of test cases T. Each of the next T lines contains 2 integers N and K.


Output

Output T lines, one corresponding to each test case, containing the required answer.

Example


Sample Input :
4
2 1
5 2
5 1
9 3

Sample Output :
1
4
9
8

Note : For the first test case, the only valid subrange is [2..2], whereas for the second test case, the valid subranges are : [2..3],[2..4],[2..5],[3..5].

Constraints

1 <= T <= 100

2 <= N <= 100000

0 <= K <= 10000

posted @ 2017-08-24 09:49  EricJeffrey  阅读(139)  评论(0编辑  收藏  举报