Let's define the function :
= , , where x is a prime number between l and r inclusive.
In Short, for each function you need to find the summation of all primes between the integers l and r inclusive.
Now, you shall be given multiple queries. In each query, you shall be given the integers l and r and you need to find the result of the function
Example:
Input: n = 2, queries = {{1, 6}, {4, 13}}
Output:
10 36
Approach:
C++
#include <bits/stdc++.h>using namespace std;//use MAXN = 1000000const int MAXN = 100000;bool prime[MAXN+1];void primeInitialize(){memset(prime, true, sizeof(prime));prime[0] = false;prime[1] = false;for (long long i = 2; i * i <= MAXN; i++){if (prime[i]){for (long long j = i * i; j <= MAXN; j += i)prime[j] = false;}}}void sumOfPrime(long long n,vector<vector<long long>> &queries){long long sum[MAXN+1] = {0};for (long long i = 2; i <= MAXN; i++){if (prime[i])sum[i] = i + sum[i - 1];elsesum[i] = sum[i - 1];}for (long long i = 0; i < n; i++){long long l = queries[i][0];long long r = queries[i][1];long long ans1 = sum[r];long long ans2 = sum[l - 1];cout << ans1 - ans2 << "\n";}}int main(){long long n = 2;vector<vector<long long>> queries = {{1, 6}, {4, 13}};primeInitialize();sumOfPrime(n, queries);return 0;}
No comments:
Post a Comment