fork download
  1. #include <bits/stdc++.h>
  2. //Here, we are solving the Prime Visits question
  3. //We have to find number of prime numbers in the range a-b for each query
  4. //So the optimised brute force approach is using prime sieve and cal number of prime b/w a and b for each query
  5. //But this would be of the order O(Q.N), where N = b-a, and lets say if N = 10^6 and Q=1000
  6. //Then order becomes 10^9 ====> TLE
  7.  
  8. //So optimised approach is to precompute the array of primes usinng prime sieve over a large range
  9. //Take an array of cummulative sum that stores the count of prime numbers upto an index i
  10. //Then number of prime numbrs in the a-b is given by csum[b] - csum[a-1]
  11. //For this approach, Complexity is O(Q+N) N for prime sieve and Q for queries
  12.  
  13.  
  14. using namespace std;
  15. #define ll long long
  16.  
  17. void prime_sieve(int *p)
  18. {
  19. p[0] = p[1] = 0; //0 and 1 are not primes
  20. p[2] = 1; //2 is a prime number
  21.  
  22. //Now, we can skip all even numbers because they can never be prime
  23. //But, odd numbers can be potential prime numbers
  24. //Therefore, initially marking all odd numbers as 1
  25. for(ll i=3; i<=1000000; i+=2)
  26. {
  27. p[i] = 1;
  28. }
  29. //sieve approach
  30. for(ll i=3; i<=1000000; i+=2)
  31. {
  32. if(p[i])//current number is prime
  33. {
  34. for(ll j=i; j*i<=1000000; j++)
  35. {
  36. p[i*j] = 0;
  37. }
  38. }
  39. }
  40.  
  41. }
  42. int main() {
  43. int p[1000005] = {0};
  44. prime_sieve(p);
  45.  
  46. int csum[1000005] = {0};
  47. for(ll i=1; i<=1000000; i++)
  48. {
  49. csum[i] = csum[i-1] + p[i];
  50. }
  51.  
  52. int q,a,b;
  53. cin>>q;
  54.  
  55. while(q--)
  56. {
  57. cin>>a>>b;
  58. cout<<csum[b]-csum[a-1]<<"\n";
  59. }
  60.  
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 11208KB
stdin
2
1 10
11 20
stdout
4
4