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
- C# | Count the number of key/value pairs in HybridDictionary
- C# | Count the number of key/value pairs in the Hashtable
- Count pairs with Bitwise XOR as ODD number
- Count pairs with Bitwise OR as Even number
- Count pairs with sum as a prime number and less than n
- Count pairs with Bitwise AND as ODD number
- Count all pairs of adjacent nodes whose XOR is an odd number
- Count number of equal pairs in a string
- Count number of ordered pairs with Even and Odd Sums
- Count number of ordered pairs with Even and Odd Product
- Count number of distinct pairs whose sum exists in the given array
- Count pairs of natural numbers with GCD equal to given number
- Count and Toggle Queries on a Binary Array
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.