In this problem, we are given a number N. Our task is to create a program to find the maximum sum of distinct numbers with LCM as N in C++.
Problem Description
Here, we need to find the sum of maximum numbers that have N as the Lowest Common Multiple (LCM).
Let’s take an example to understand the problem,
Input
N = 10
Output
18
Explanation
Maximum sum with LCM 10 is 1 + 2 + 5 + 10 = 18
Solution Approach
A simple solution to the problem would be using the idea that if we want the number N as LCM, then we need to take all the distinct divisors of N. And add them up to get the maxSum.
For this we will find all the factors of N. And then add them up, this will be given the maximum as we have considered all the numbers that can contribute to the LCM being N.
Example
Program to illustrate the working of our solution,
#include <iostream>
using namespace std;
int calcFactorSum(int N){
int maxSum = 0;
for (int i = 1; i*i <= N; i++){
if (N % i == 0) {
if (i == (N/i))
maxSum = maxSum + i;
else
maxSum = maxSum + i + (N/i);
}
}
return maxSum;
}
int main(){
int N = 42;
cout<<"The sum of distinct numbers with LCM as "<<N<<" is "<<calcFactorSum(N);
return 0;
}Output
The sum of distinct numbers with LCM as 42 is 96