Given a positive even integer N, the task is to find the number of pairs (i, j) from the range [1, N] such that the product of i and L1 is the same as the product of j and L2 where i < j and L1 and L2 any number from the range [1, N/2].
Input: N = 4
The possible pairs satisfying the given criteria are:
- (1, 2): As 1 < 2, and 1*2 = 2*1 where L1 = 2 and L2 = 1.
- (2, 4): As 2 < 4 and 2*2 = 4*1 where L1 = 2 and L2 = 1.
Therefore, the total count is 2.
Input: N = 6
Naive Approach: The given problem can be solved based on the following observations:
Let i * L1 = j * L2 = lcm(i, j) — (1)
⇒ L1 = lcm(i, j)/ i
= j/gcd(i, j)
Similarly, L2 = i/gcd(i, j)
Now, for the condition to be satisfied, L1 and L2 must be in the range [1, N/2].
Therefore, the idea is to generate all possible pairs (i, j) over the range [1, N] and if there exist any pair (i, j) such that the value of i/gcd(i, j) and j/gcd(i, j) is less than N/2, then increment the count of pairs by 1. After checking for all the pairs, print the value of the count as the result.
Time Complexity: O(N2*log N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by using Euler’s Totient function. There exist the following 2 cases for any pair (i, j):
- Case 1: If the pair (i, j) lies in the range [1, N/2], then all the possible pairs formed will satisfy the given condition. Therefore, the total count of pairs is given by (z*(z – 1))/2, where z = N/2.
- Case 2: If all possible pairs (i, j) lies in the range [N/2 + 1, N] having gcd(i, j) is greater than 1 satisfy the given conditions.
Follow the steps below to count the total number of this type of pairs:
- Compute Φ for all numbers smaller than or equal to N by using Euler’s Totient function for all numbers smaller than or equal to N.
- For a number j, the total number of possible pairs (i, j) can be calculated as (j – Φ(j) – 1).
- For each number in the range [N/2 + 1, N], count the total number pairs using the above formula.
- After completing the above steps, print the sum of values obtained in the above two steps as the result.
Below is the implementation of the above approach:
Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.