- Related Questions & Answers
- Find count of Almost Prime numbers from 1 to N in C++
- Count total number of digits from 1 to N in C++
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N in C++
- Count pairs of numbers from 1 to N with Product divisible by their Sum in C++
- Count pairs with sum as a prime number and less than n in C++
- Print prime numbers from 1 to N in reverse order
- Find product of prime numbers between 1 to n in C++
- Count number of bits changed after adding 1 to given N in C++
- C++ Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements From 1 to N
- Program to count number of fraction pairs whose sum is 1 in python
- Python program to count total set bits in all number from 1 to n.
- Program to find sum of prime numbers between 1 to n in C++
- Program to print ‘N’ alphabet using the number pattern from 1 to n in C++
- Minimum insertions to make a Co-prime array in C++
- All possible co-prime distinct element pairs within a range [L, R]?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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.

#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; }

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

Advertisements