VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-distinct-numbers-lcm-numbers-n/

⇱ Maximum sum of distinct numbers such that LCM of these numbers is N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum of distinct numbers such that LCM of these numbers is N

Last Updated : 5 Jun, 2026

Given a positive integer n, find the maximum sum of distinct positive integers not exceeding n such that the LCM of all the selected integers is exactly n.

Examples:

Input: n = 2
Output: 3
Explanation: The valid numbers whose LCM is 2 are 1 and 2, and their sum is 1 + 2 = 3.

Input: n = 5
Output: 6
Explanation: The valid numbers whose LCM is 5 are 1 and 5, and their sum is 1 + 5 = 6.

[Naive Approach] Generate All Subsets - O(2^n × n) Time and O(n) Space

The idea is to try every possible subset of numbers from 1 to n. For each subset, we compute its LCM and check whether it equals n. If it does, we compute the sum and update the maximum answer.


Output
6

[Expected Approach] Sum of All Divisors - O(√n) Time and O(1) Space

The key idea is to avoid checking all subsets and use a simple property of LCM. For the LCM to be exactly n, every selected number must be a divisor of n, otherwise it will increase the LCM beyond n. Hence, only divisors are valid choices. Since adding more valid numbers increases the sum without changing the LCM, the optimal solution is to include all divisors of n to maximize the sum.

  • Initialize sum = 0
  • Iterate from 1 to √n
  • If i is a divisor of n:
  • Add i to the sum
  • Add n / i if it is different from i
  • Return the final sum

Consider integer: n = 12

Iterate from 1 to √12 ≈ 3

  • For i = 1: 12 % 1 == 0 -> Add: 1 and 12 -> Sum = 13
  • For i = 2: 12 % 2 == 0 -> Add: 2 and 6 -> Sum = 21
  • For i = 3: 12 % 3 == 0 -> Add: 3 and 4 -> Sum = 28
  • For i = 4 to 12: Already covered through pairs -> no new additions

Final Answer:28


Output
28
Comment
Article Tags:
Article Tags: