CHEFLCM - Editorial



Author: Abhra Dasgupta
Tester: Sergey Kulik
Editorialist: Adury Surya Kiran






For a given positive integer N, what is the maximum sum of distinct numbers such that the Least Common Multiple of all these numbers is N.


As N is LCM of all the numbers, all of them will be divisors of N. As each divisor can occur only once, the answer will be sum of all the divisors of N.

Subtask 1

As N <= 10^5, we can iterate through each i from 1 to N and add all divisors. Complexity is O(N) per test case.

Subtask 2

We can observe that for each pair of divisors (p, q), such that p * q = N, either p <= sqrt(N) or q <= sqrt(N), else p * q will be greater than N. Also we can check that for each divisor p, there exists a distinct q such that p * q = N.

Without loss of generality let us assume p <= q. We can iterate for each p from 1 to sqrt(N) and if p is a divisor of N, then add both p and N / p to the answer. Complexity is O(sqrt(N)) per test case.

C++ Code

using namespace std;
int main(){
    int t;
    for(int i = 1; i <= t; i++){
        int n, p;
        long long sum = 0;
        cin >> n;
        for(p = 1; p * p <= n; p++){
            if(n % p == 0){
                sum += p;
                if(p != n / p){
                    sum += n / p;
        cout << sum << '\n';
    return 0;

Common Mistakes:

  1. We should check that p is not equal to N / p while adding N / p.
  2. The answer can exceed the range of integer in C++, so it should be kept as long long.


Author’s solution
Tester’s solution

1 Like

Can please anyone point out my fault. My code ( ) seems quite the same to the one given above.

Awesome editorial !!shook me to core

@debverine instead of ‘int’ if you used ‘long’ then its easily passes all test cases

thank you @viperx . I made a terrible mistake :frowning:

@ikagotso I think there is a precision issue was with division in every step as of iteration in the formula as the division is not integral.
I made slight change to your code and it got accepted. Check out the submission here

1 Like

Though this is a very simple approach,but still i want a clearification on it.partially correct.It shows TLE for higher subtask.

Terima kasih dan salam kenal.
codechef Link

code Link

my solution is accepted.
I used same logic but i got WA on

please anyone tell me why it was gave Wrong ans ?
Thanks in advance.