Given an integer X, the task is to find two integers A and B such that sum of these two numbers is X and the LCM of A and B is maximum.
Input: X = 15
Output: 7 8
7 + 8 = 15 and LCM(7, 8) = 56 is the maximum possible.
Input: X = 30
Output: 13 17
13 + 17 = 30 and LCM(13, 17) = 221 is the maximum possible.
Naive Approach: The simplest approach is to use Two Pointers to find the pair of integers A and B with a given sum X and maximum possible LCM. Below are the steps:
- Initialize A and B as 1 and X–1 respectively.
- Run a loop, while, A is less than and equal to B.
- At each iteration calculate the LCM of A and B, then increment A by 1 and decrement B by 1.
- Print the A and B corresponding to the maximum LCM.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above naive approach the idea is to use some mathematical observations. The LCM of two co-prime integers is equal to the product of the two integers. Thus, the problem can be simplified to finding two co-prime integers A and B such that A+B = X and A×B is maximum. Below are the steps:
- If X is odd, then A = floor(X/2) and B = floor(X/2) + 1.
- Otherwise, if X is even, then
- If floor(X/2) is even, then A = floor(X/2) – 1 and B = floor(X/2) + 1.
- Otherwise, if floor(X/2) is odd, then A = floor(X/2) – 2 and B = floor(X/2) + 2.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
- Sum of LCM(1, n), LCM(2, n), LCM(3, n), ... , LCM(n, n)
- Find two numbers with the given LCM and minimum possible difference
- Minimum replacement of pairs by their LCM required to reduce given array to its LCM
- Minimum LCM and GCD possible among all possible sub-arrays
- Maximum sum of distinct numbers such that LCM of these numbers is N
- Given GCD G and LCM L, find number of possible pairs (a, b)
- Find two distinct numbers such that their LCM lies in given range
- Count of all possible pairs having sum of LCM and GCD equal to N
- Maximum sum of distinct numbers with LCM as N
- Program to find LCM of two numbers
- Program to find LCM of two Fibonnaci Numbers
- Program to find the LCM of two prime numbers
- Minimum number to be added to minimize LCM of two given numbers
- Maximum LCM among all pairs (i, j) of first N natural numbers
- Finding LCM of more than two (or array) numbers without using GCD
- LCM of two large numbers
- Minimum possible value of max(A, B) such that LCM(A, B) = C
- Find three integers less than or equal to N such that their LCM is maximum
- Maximum LCM among all pairs (i, j) from the given Array
- Find LCM of rational numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.