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
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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if a number can be expressed as 2^x + 2^y
- Minimum positive integer value possible of X for given A and B in X = P*A + Q*B
- How to compute mod of a big number?
- Next higher number using atmost one swap operation
- Number of co-prime pairs in an array
- Numbers with sum of digits equal to the sum of digits of its all prime factor
- Minimum number of square tiles required to fill the rectangular floor
- Final cell position in the matrix
- Number of Permutations such that no Three Terms forms Increasing Subsequence
- Check if the first and last digit of the smallest number forms a prime