VOOZH about

URL: https://www.geeksforgeeks.org/dsa/series-largest-gcd-sum-equals-n/

⇱ Series with largest GCD and sum equals to n - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Series with largest GCD and sum equals to n

Last Updated : 23 Jun, 2025

Given integers n and m, construct a strictly increasing sequence of m positive integers with sum exactly equal to n such that the GCD of the sequence is maximized. If multiple sequences have the same maximum GCD, return the lexicographically smallest one. If not possible, return -1.

Examples :

Input : n = 24, m = 3
Output : [4, 8, 12]
Explanation : 3, 6, 15 is also a possible sequence having gcd as 3, but 4, 8, 12 has a gcd of 4 which is maximum possible among all.

Input : n = 6, m = 4
Output : [-1 ]
Explanation: It is not possible, as the smallest possible GCD sequence would be (1, 2, 3, 4), which gives a sum greater than n. Hence, the answer is -1.

Approach:

The idea is to form the sequence as GCD × [1, 2, ..., m] and find the largest possible GCD such that the total sum doesn't exceed n. We then construct the sequence using this GCD, adjusting the last element to match the exact sum. If such a sequence isn't possible, we return -1.

Step by Step Implementations:

  • Compute the minimum sum of the first m natural numbers: minSum= (m×(m+1))/2, if minSum > n then output will be -1.
  • Let b = n / minSum. Iterate over all divisors of n which is less than or equal to b to find the largest such divisor r.
  • Build the sequence r × [1, 2, ..., m - 1] as the initial sequence (i.e., [r×1, r×2, r×3, r×4 ,..., r×(m-1)]
  • Make the last element: lastEle = n − r × (m×(m-1))/2.
  • Hence the final sequence is - [r×1, r×2, r×3, r×4 ,..., r×(m-1), lastEle].

Output
4 8 12 

Time Complexity: O(√n + m), finding all divisors of n takes O(√n) time, and constructing the sequence takes O(m) time.
Space Complexity: O(m)

Comment