# Maximum sum of distinct numbers such that LCM of these numbers is N in C++

C++Server Side ProgrammingProgramming

In this problem, we are a number N. Our task is to create a program to find the Maximum sum of distinct numbers such that LCM of these numbers is N in C++.

## Problem Description

We need to find the sum of all factors of the number N. And add all distinct to find the maximum sum.

Let’s take an example to understand the problem,

## Input

N = 12

## Output

28

## Explanation

All distinct factors of N are 1, 2, 3, 4, 6, 12.
Sum = 1 + 2 + 3 + 4 + 6 + 12 = 28

## Solution Approach

A simple solution will be finding all the factors of the number and then adding all distinct factors to find the result.

For this, we will iterate till the square root of N. And check if the number divides N. If yes, check if it is distinct, if yes add the number and the division quotient Otherwise add the number. Return the final maxSum.

## Example

Program to illustrate the working of our solution,

Live Demo

#include <iostream>
using namespace std;
int calcMaxSumForLCM(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 = 17;
cout<<"The sum of distinct numbers such that LCM if these numbers is "<<N<<" is "<<calcMaxSumForLCM(N);
return 0;
}

## Output

The sum of distinct numbers such that LCM if these numbers is 17 is 18
Published on 22-Jul-2020 11:57:53