# Queries to count the number of unordered co-prime pairs from 1 to N in C++

C++Server Side ProgrammingProgramming

In this problem, we are given Q queries each contains a number N. Our task is to create a program to solve Queries to count the number of unordered coprime pairs from 1 to N in C++.

Co-prime also known as relatively prime or mutually prime are the pair of numbers that have only one factor i.e. 1.

Let’s take an example to understand the problem,

Input: Q = 2, queries = [5, 6]

Output: 10

## Explanation

The pairs are : (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (3, 5), (4, 5)

## Solution Approach

The most promising solution to the problem is using Euler’s Totient Function phi(N). phi(N) calculates the total number of co-primes until the given value N. The Euler’s totient function is,

$$𝛷(𝑁) = 𝑁 ∏𝑁/𝑁 (1 −),$$

Where p is all prime factors of N.

Now, we will pre-calculate the value of the count of the number of unordered coprime pairs till N. And then find the value of each query from the precalculated array.

## Example

Live Demo

#include <iostream>
using namespace std;
#define N 10001
int phi[N];
int CoPrimePairs[N];
void computePhi(){
for (int i = 1; i < N; i++)
phi[i] = i;
for (int p = 2; p < N; p++) {
if (phi[p] == p) {
phi[p] = p - 1;
for (int i = 2 * p; i < N; i += p) {
phi[i] = (phi[i] / p) * (p - 1);
}
}
}
}
void findCoPrimes() {
computePhi();
for (int i = 1; i < N; i++)
CoPrimePairs[i] = CoPrimePairs[i - 1] + phi[i];
}
int main() {
findCoPrimes();
int Q = 3;
int query[] = { 5, 7, 9};
for (int i = 0; i < Q; i++)
cout<<"For Query "<<(i+1)<<": Number of prime pairs is "<<CoPrimePairs[query[i]]<<endl;
return 0;
}

## Output

For Query 1: Number of prime pairs is 10
For Query 2: Number of prime pairs is 18
For Query 3: Number of prime pairs is 28
Published on 14-Aug-2020 11:34:23