Maximum sum of distinct numbers with LCM as N - GeeksforGeeks
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.
Read full article from Maximum sum of distinct numbers with LCM as N - GeeksforGeeks
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.
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.
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.
int
getMaximumSumWithLCMN(
int
N)
{
int
sum = 0;
int
LIM =
sqrt
(N);
// find all divisors which divides 'N'
for
(
int
i = 1; i <= LIM; i++)
{
// if 'i' is divisor of 'N'
if
(N % i == 0)
{
// if both divisors are same then add
// it only once else add both
if
(i == (N / i))
sum += i;
else
sum += (i + N / i);
}
}
return
sum;
}
Read full article from Maximum sum of distinct numbers with LCM as N - GeeksforGeeks