Given a number N. The task is to find the number of unordered coprime pairs of integers from 1 to N. There can be multiple queries.
Input: 3 Output: 4 (1, 1), (1, 2), (1, 3), (2, 3) Input: 4 Output: 6 (1, 1), (1, 2), (1, 3), (1, 4), (2, 3), (3, 4)
Approach: Here Euler’s Totient Function will be helpful. Euler’s totient function denoted as phi(N), is an arithmetic function that counts the positive integers less than or equal to N that are relatively prime to N.
The idea is to use the following properties of Euler Totient function i.e.
- The formula basically says that the value of Φ(n) is equal to n multiplied by product of (1 – 1/p) for all prime factors p of n. For example value of Φ(6) = 6 * (1-1/2) * (1 – 1/3) = 2.
- For a prime number p, Φ(p) is p-1. For example Φ(5) is 4, Φ(7) is 6 and Φ(13) is 12. This is obvious, gcd of all numbers from 1 to p-1 will be 1 because p is a prime.
Now, find the sum of all phi(x) for all i between 1 to N using prefix sum method. Using this, one can answer in o(1) time.
Below is the implementation of above approach.
Number of unordered coprime pairs of integers from 1 to 3 are 4 Number of unordered coprime pairs of integers from 1 to 4 are 6
- Count unordered pairs (i,j) such that product of a[i] and a[j] is power of two
- Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
- Largest number less than or equal to N/2 which is coprime to N
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Count pairs with sum as a prime number and less than n
- Given two arrays count all pairs whose sum is an odd number
- Count pairs with Bitwise AND as ODD number
- Count number of ordered pairs with Even and Odd Sums
- Count number of ordered pairs with Even and Odd Product
- Count pairs of natural numbers with GCD equal to given number
- Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
- Queries on sum of odd number digit sums of all the factors of a number
- Composite XOR and Coprime AND
- Count pairs with Odd XOR
- Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.