2 and 4 are coprime-twin pairs.
1 and 2 are not coprime-twin pairs.
The score of a sequence a1, a2, .. an is the number of indices (i, j) such that i < j and the pair (ai, aj) forms a coprime-twin pair.
You are given an array A of positive integers and Q queries of the form L, R. For each query, determine the score of the subarray [L, R] inclusive.
Note: A subarray is a contiguous non-empty segment of the array.
The first line contains a single integer ‘T’ denoting the number of test cases to be run. Then the test cases follow.
The first line of each test case contains two space-separated integers N and Q which denote the number of elements in the array A and the number of queries you need to answer respectively.
The next line contains N space-separated integers denoting the array a1, a2, … an.
The next Q lines contain two integers each - Li and Ri, the parameters of the ith query.
For each test case, Q lines
For each of the next Q lines, print a single integer denoting the answer for the ith query.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N, Q <= 10^4
1 <= Ai <= 10^6
1 <= L <= R <= N
Time Limit: 1 sec.
Two numbers are called co-prime twins if and only if the set of primes in its prime factorization is equal.
So for any number, we need to reduce any power of a prime to only single if we want to compare the sets.
If x = p1^x1*p2^x2 … pk^xk
we can reduce it to
x = p1 * p2 * p, .. pk
Now, this can be done using pre-computation of primes using a sieve of Eratosthenes.
Now we just need to count for each query the number of equal pairs in that range which can be done using a count array..
Algorithm:
coprimeTwins (Q, A) returns the answer for each of the queries in Q.
precompute(reduced) returns an array where each index stores its reduced form.
We will use the idea of approach 1 to reduce the numbers to only one power of each prime. After that instead of answering each query at the time of input, we take all the queries at once and try to answer them in Mo’s algorithm order.
Suppose we want to extend the interval from [L, R] to [L, R + 1] we increase the count of answers by cnt[arr[R + 1]] because that many numbers of new pairs will be added. We follow a similar algorithm to shrink the interval.
coprimeTwins (Q, A) returns the answer for each of the queries in Q.
precompute(reduced) returns an array where each index stores its reduced form.