- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum sum of distinct numbers with LCM as N in C++
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
- Related Articles
- Maximum sum of distinct numbers such that LCM of these numbers is N in C++
- Find two numbers with sum and product both same as N in C++
- Find two numbers with sum and product both same as N in C++ Program
- C++ program to find two numbers with sum and product both same as N
- Find four factors of N with maximum product and sum equal to N in C++
- Sum of sum of first n natural numbers in C++
- C++ find four factors of N with maximum product and sum equal to N .
- Find sum of Series with n-th term as n^2 - (n-1)^2 in C++
- Represent a number as a Sum of Maximum Possible Number of Prime Numbers in C++
- C++ Program to Find the GCD and LCM of n Numbers
- Print all possible sums of consecutive numbers with sum N in C++
- Find four factors of N with maximum product and sum equal to N - Set-2 in C++
- Maximum sum by adding numbers with same number of set bits in C++
- Find maximum N such that the sum of square of first N natural numbers is not more than X in C++
- Maximum subarray sum in O(n) using prefix sum in C++

Advertisements