VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-ordered-pairs-of-numbers-with-a-given-lcm/

⇱ Count ordered pairs of numbers with a given LCM - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count ordered pairs of numbers with a given LCM

Last Updated : 15 Jul, 2025

Given an integer N, the task is to count the total number of ordered pairs such that the LCM of each pair is equal to N.

Examples:

Input: N = 6
Output:
Explanation: 
Pairs with LCM equal to N(= 6) are {(1, 6), (2, 6), (2, 3), (3, 6), (6, 6), (6, 3), (3, 2), (6, 2), (6, 1)} 
Therefore, the output is 9.

Input: N = 36
Output: 25

Brute Force Approach:

A brute force approach to solve this problem would be to consider all possible pairs of integers (a,b) such that 1 <= a,b <= N, and then check if their LCM is equal to N. If it is, then count it as a valid pair.

Below is the implementation of the above approach:


Output
9

Time Complexity: O(N^2)

Auxiliary Space: O(1)

Approach: The problem can be solved based on the following observations:

Consider an ordered pair(X, Y). 
X = P1a1 * P2a2 * P3a3 *.....* Pnan 
Y = P1b1 * P2b2 * P3b3 *.....* Pnbn
Here, P1, P2, ....., Pn are prime factors of X and Y. 
LCM(X, Y) = P1max(a1, b1)  * P2max(a2, b2) *..........*Pnmax(an, bn)
Therefore, LCM(X, Y) = N = P1m1 * P2m2 * P3m3 *.....* Pnmn

Therefore, total number of ordered pairs (X, Y) 
= [{(m1 + 1)2 - m12} * {(m2 + 1)2 - m22} * ......* {(mn + 1)2 - mn2} ]
= (2*m1+1) * (2*m2+1) * (2*m3+1) * ........* (2*mn+1).

Follow the steps below to solve the problem:

  1. Initialize a variable, say, countPower, to store the power of all prime factors of N.
  2. Calculate the power of all prime factors of N.
  3. Finally, print the count of ordered pairs(X, Y) using the aforementioned formula.

Below is the implementation of the above approach:
 


Output
25

Time Complexity: O(√N) 
Auxiliary Space: O(1)

Comment
Article Tags: