Two special cases dominate:

  • — the number of divisors,
  • — the sum of divisors.

From the factorisation

For :

All are multiplicative.

Computing for all

The harmonic-series sieve — :

vector<int> d(N + 1, 0);
for (int i = 1; i <= N; i++)
    for (int j = i; j <= N; j += i) d[j]++;          // count of divisors
 
vector<long long> sig(N + 1, 0);
for (int i = 1; i <= N; i++)
    for (int j = i; j <= N; j += i) sig[j] += i;     // sum of divisors

The total work is . This “iterate over multiples of each ” pattern is the single most useful loop in divisor problems.

For , use a linear sieve tracking the exponent of the smallest prime factor.

Enumerating the divisors of one

vector<long long> divisors(long long n) {
    vector<long long> d;
    for (long long i = 1; i * i <= n; i++)
        if (n % i == 0) { d.push_back(i); if (i != n / i) d.push_back(n / i); }
    sort(d.begin(), d.end());
    return d;
}

. For up to , factor first and generate divisors from the exponent vectors — after factorisation.

Size bounds

max achieved at
32840
240720 720
1344735 134 400
6720
103 680

Average: . So “loop over all divisors of every ” is , not .

FunctionMeaning
number of divisors
sum of divisors
aliquot sum — sum of proper divisors
number of distinct prime factors
number of prime factors with multiplicity
product of distinct primes

Perfect numbers satisfy (equivalently ): 6, 28, 496, 8128. Every even perfect number is with a Mersenne prime (Euclid-Euler). Whether an odd perfect number exists is a famous open problem.

Amicable pairs satisfy and : (220, 284).

Useful identities

That last identity is the workhorse: the number of pairs with equals , computable in with the Dirichlet hyperbola method:

The same method computes and other divisor-convolution sums in .

Problem patterns

ProblemApproach
Count numbers with exactly divisorssieve , then count
Smallest number with divisorssearch over exponent patterns of the first primes
for hyperbola method,
Divisors of Legendre’s formula per prime
Number of divisors of a productfactor each, add exponents
Sum over with iterate multiples,
Highly composite numbersrecursive search over non-increasing exponents

The multiples loop is not

Beginners often avoid for i, for j += i fearing quadratic cost. It is — for that is operations, entirely affordable. Recognising this unlocks a large class of otherwise-hard problems.

See also: Integer Factorization · Möbius Function · Sieve Techniques