Given a number N, the task is to find out maximum sum of distinct numbers such that the Least Common Multiple of all these numbers is N.
Input : N = 12 Output : 20 Maximum sum which we can achieve is, 1 + 2 + 3 + 4 + 6 + 12 = 28 Input : N = 15 Output : 24
We can solve this problem by observing some cases, As N needs to be LCM of all numbers, all of them will be divisors of N but because a number can be taken only once in sum, all taken numbers should be distinct. The idea is to take every divisor of N once in sum to maximize the result.
How can we say that the sum we got is maximal sum? The reason is, we have taken all the divisors of N into our sum, now if we take one more number into sum which is not divisor of N, then sum will increase but LCM property will not be hold by all those integers. So it is not possible to add even one more number into our sum, except all divisor of N so our problem boils down to this, given N find sum of all divisors, which can be solved in O(sqrt(N)) time.
So total time complexity of solution will O(sqrt(N)) with O(1) extra space.
Code is given below on above stated concept. Please refer this post for finding all divisors of a number.
This article is contributed by Utkarsh Trivedi. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sum of LCM(1, n), LCM(2, n), LCM(3, n), ... , LCM(n, n)
- Maximum sum of distinct numbers such that LCM of these numbers is N
- Minimum replacement of pairs by their LCM required to reduce given array to its LCM
- Find two distinct numbers such that their LCM lies in given range
- Find two numbers with given sum and maximum possible LCM
- Number of distinct integers obtained by lcm(X, N)/X
- Maximum LCM among all pairs (i, j) of first N natural numbers
- Count numbers whose maximum sum of distinct digit-sum is less than or equals M
- Find three integers less than or equal to N such that their LCM is maximum
- Maximum length subarray with LCM equal to product
- Sum of M maximum distinct digit sum from 1 to N that are factors of K
- Finding LCM of more than two (or array) numbers without using GCD
- Program to find LCM of two numbers
- Find LCM of rational numbers
- LCM of two large numbers
- Program to find LCM of 2 numbers without using GCD
- LCM of N numbers modulo M
- Program to find LCM of two Fibonnaci Numbers
- Find two numbers with the given LCM and minimum possible difference
- Program to find the LCM of two prime numbers
Improved By : nitin mittal