Ninja And The LCM

Easy
0/40
Average time to solve is 15m
profile
Contributed by
25 upvotes
Asked in companies
D.E.ShawCarWaleArista Networks

Problem statement

Ninja has given two numbers ‘X’ and ‘Y’. He has to find the LCM of these two numbers.

LCM (Least Common Multiple) of two numbers is the smallest number that can be divisible by both numbers.

As you are his big brother. So help Ninja in calculating the LCM.

EXAMPLE:
Input: 'X' = 2,  ‘Y’=3

Output: "6"

As “6” is the smallest number that is divisible by both 2 and 3.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line will contain the integer 'T', denoting the number of test cases.

Each test case contains two space-separated integers ‘X’ and ‘Y’ 
Output format :
For each test case, print the LCM of given integers ‘X’ and ‘Y’.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 1000
1 <= ‘X’ , ‘Y’ <= 10^9
Time Limit: 1 sec
Sample Input 1 :
2
2 7
6 8
Sample Output 1 :
14
24
Explanation Of Sample Input 1 :
In test case ‘1’, before 8 to 13, all numbers are not divided by both ‘2’ and ‘7’ both. So ‘14’ is the smallest number divisible by both ‘2’ and ‘7’. So LCM of ‘2’ and ‘7’ is ‘14’.
In test case ‘2’, ‘24’ is the smallest number divisible by both ‘6’ and ‘8’ so the answer is ‘24’.
Sample Input 2 :
2
8 8
6 24
Sample Output 2 :
8
24
Hint

What if both numbers are prime numbers?

Approaches (1)
Mathematical solution

Approach: 

 

We will remove the common factors from both of them, which means that we will remove the GCD ( Greatest Common Divisor ) by dividing them by their gcd. Then they will become the co-prime numbers.

 

And LCM of two co-prime numbers is their multiplication. Then we will multiple again with gcd to get the final LCM.

 

So LCM (X, Y) = (X/GCD(X,Y) * (Y/GCD(X,Y) * GCD(X,Y). 

 

On simplify LCM(X,Y) = X * Y/GCD(X,Y). 

 

We can calculate the GCD of two numbers with the ‘ Euclidean algorithm ’, which says that:

 

GCD(A, B) = A if B == 0, else GCD(A, B) = GCD(B, A%B).


 

Algorithm :  

 

  • Find GCD of given numbers using recursion and store it in variable ‘G’.
    • Let function is GCD(X,Y)
    • Then if ‘Y’ ==0 return ‘X’
    • Else return GCD(Y, X%Y).
  • Now return X * Y/G.
Time Complexity

O(log(min(X, Y)), Where ‘X’ and ‘Y’ are the input integers.

 

As we will go at max log(min(X, Y)) recursive calls in a function.Because notice that ‘A’ mod ‘B’  for the case A >= B  is at least 2 times smaller than A.

Space Complexity

O(1).

 

As we are maintaining a constant variable to store the answer, the space complexity will be O(1).

Code Solution
(100% EXP penalty)
Ninja And The LCM
Full screen
Console