Prime Counting

Deepjoy is very much fond of prime numbers. He is fascinated by the fact that these numbers are divisible by only 

2 numbers (1 and the number itself).

His friends challenged him with a problem related to the prime numbers which he eventually cracked.

Now it's your turn to solve the problem. Let's see whether you can solve it or not!

You are given N intervals in the form of [li,ri] (for each valid i, where 1iN). Each interval contains all the integers x satisfying the condition xli,xri. Now find the intersection of all the intervals (integers common to all the intervals) and print the count of the number of primes within the common intersection interval.

Example:

Input:  n = 2, arr = {{2,10},{5,19}}
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;
#define MAX 1000001

vector<intsieve()
{
    bool isPrime[MAX];
    memset(isPrimetrueMAX);

    for (int i = 2i * i < MAX; i++)
    {
        if (isPrime[i])
        {
            for (int j = i * ij < MAX; j += i)
                isPrime[j] = false;
        }
    }

    vector<intprime;
    prime.push_back(2);
    for (int i = 3i < MAX; i += 2)
    {
        if (isPrime[i])
            prime.push_back(i);
    }
    return prime;
}

void segmentedSieve(int lint rvector<intprimes)
{
    bool isPrime[r - l + 1];
    for (int i = 0i <= r - li++)
        isPrime[i] = true;
    for (int i = 0primes[i] * (long long)primes[i] <= ri++)
    {
        int currPrime = primes[i];
        long long base = (l / currPrime) * currPrime;
        if (base < l)
            base += currPrime;

        for (long long j = basej <= rj += currPrime)
        {
            isPrime[j - l] = false;
        }
        if (base == currPrime)
            isPrime[base - l] = true;
    }
    int ans = 0;
    for (int i = 0i <= r - li++)
    {
        if (isPrime[i])
            ans++;
    }
    if (l == 1)
        ans--;
    cout << ans << endl;
}

void primeCount(int nvector<vector<int>> &arr)
{
    vector<intprime = sieve();
    int low = INT_MIN;
    int high = INT_MAX;

    for (int i = 0i < ni++)
    {
        int x = arr[i][0]y = arr[i][1];
        low = max(lowx);
        high = min(highy);
    }
    if (low > high)
        cout << -1 << endl;
    else
        segmentedSieve(lowhighprime);
}
int main()
{

    int n = 2;

    vector<vector<int>> arr = {{210}, {519}};

    primeCount(narr);

    return 0;
}


No comments:

Post a Comment