Practice › Basics
Sum of Divisors of All Numbers up to N
Medium · Basics · Asked at Amazon, Google, Codenation
Let σ(k) be the sum of all positive divisors of k (σ(6) = 1 + 2 + 3 + 6 = 12). Print σ(1) + σ(2) + … + σ(n).
Input
A single integer n.
Output
The total.
Constraints
- 1 ≤ n ≤ 10^6
Swap the order of summation: every d from 1 to n divides exactly ⌊n/d⌋ of the numbers 1 … n, so the total is Σ d × ⌊n/d⌋ — one loop. The answer is about 8 × 10^11, so use 64-bit integers.
Example 1
Input
4
Output
15
Example 2
Input
1
Output
1
Hints
- Summing the divisors of every k separately is O(n √n).
- Turn it around: how many numbers ≤ n does d divide?
- Exactly ⌊n/d⌋ of them, each contributing d.
Approach
The total equals Σ over d = 1 … n of d · ⌊n/d⌋, because d appears as a divisor of d, 2d, 3d, …, ⌊n/d⌋·d. One loop computes it. The result is about (π²/12) n² ≈ 8.2 × 10^11 for n = 10^6, so use a 64-bit accumulator. (Grouping equal values of ⌊n/d⌋ even gives O(√n).)
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n, total = 0;
cin >> n;
for (long long d = 1; d <= n; d++) total += d * (n / d);
cout << total << "\n";
return 0;
}Python solution
n = int(input())
print(sum(d * (n // d) for d in range(1, n + 1)))Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong(), total = 0;
for (long d = 1; d <= n; d++) total += d * (n / d);
System.out.println(total);
}
}Solve Sum of Divisors of All Numbers up to N online · All practice problems