Skip to content

Number Of Divisors

:::note Question Given n1018n \le 10^{18}, find number of divisors of nn. :::

:::info Resources

:::

The complexity of the following is O(n)\mathcal{O}(\sqrt{n}).

Naive Solution
void solve() {
int n; cin >> n;
int an = 0;
for (int i = 1; i * i <= n; ++i) {
if (n % i == 0) {
an += 2;
if (i * i == n) --an;
}
}
cout << an << '\n';
}

O(n13)\mathcal{O}(n^{\frac{1}{3}}) solution

Section titled “O(n13)\mathcal{O}(n^{\frac{1}{3}})O(n31​) solution”
  • Let’s split n=x×yn = x \times y where xx contains only prime factors in range [2,n13][2, n^{\frac{1}{3}}] and rest of primes in yy.
  • Let f(n)f(n) denote our answer. Now, since xx and yy are coprime, f(n)=f(x)×f(y)f(n) = f(x) \times f(y).
  • f(x)f(x) can be calculated directly similar to naive solution in O(n13)\mathcal{O}(n^{\frac{1}{3}}).
  • Observe that yy falls into one of these cases:
    • yy is prime     \implies f(y)=2f(y) = 2
    • yy is square of prime     \implies f(y)=3f(y) = 3
    • yy is product of two distinct primes     \implies f(y)=4f(y) = 4
  • This is because there can be at max only two divisors of yy, otherwise one of them surely must be n13\le n^{\frac{1}{3}}.
//pseudocode -- will update later
void solve() {
int n; cin >> n;
vector<int> pr; // all primes till 10^6
int an = 1;
for (auto &p : pr) {
if (p * p * p > n) break;
int cn = 1;
while (n % p == 0) { n /= p; ++cn; }
an *= cn;
}
// use miller-rabin
if (n is prime) { an *= 2; }
else if (n is square of prime) { an *= 3; }
else an *= 4;
cout << an << '\n';
}