CF385C Bear and Prime Numbers

Ideas:

It is necessary to have a correct understanding of the time complexity of the Ehrlich sieve method (O(nlog(log(n)))), I thought it must be timed out, and the result can pass.

accomplish:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 bool is_prime[10000005];
 5 vector<int> prime;
 6 int num[10000005], ans[10000005];
 7 void sieve(int n)
 8 {
 9     for (int i = 0; i <= n; i++) is_prime[i] = true;
10     is_prime[0] = is_prime[1] = false;
11     for (int i = 2; i <= n; i++)
12     {
13         if (is_prime[i])
14         {
15             prime.push_back(i);
16             for (int j = 2 * i; j <= n; j += i) is_prime[j] = false;
17         }
18     }
19 }
20 int main()
21 {
22     sieve(10000000);
23     int n, m, x, a, b;
24      while (scanf( " %d " , &n) != EOF)
 25      {
 26          memset(num, 0 , sizeof num);
 27          memset(ans, 0 , sizeof ans);
 28          int l = prime.size();
 29          for ( int i = 0 ; i < n; i++) { scanf( " %d " , &x); num[x]++ ; }
 30          for ( int i = 0 ; i < l; i++ ) // this The segment code is the same as the prime number sieve method
31         {
32             int now = prime[i];
33             for (int j = now; j <= 10000000; j += now)
34             {
35                 if (num[j]) ans[now] += num[j];
36             }
37         }
38         for (int i = 1; i <= 10000000; i++) ans[i] += ans[i - 1];
39         scanf("%d", &m);
40         for (int i = 0; i < m; i++)
41         {
42             scanf("%d %d", &a, &b);
43             if (a > b) { puts("0"); continue; }
44             a = min(a, 10000000); b = min(b, 10000000);
45             printf("%d\n", ans[b] - ans[a - 1]);
46         }
47     }
48     return 0;
49 }

 

Guess you like

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