Number of divisors#4742

Number of divisors (Editorial)

Let be the number of divisors of . Obviously, d(1) = 1.

Let be a prime integer. Then has two divisors: and . Therefore, d(p) = 2.

Let n = p^k be a power of a prime number. Then has k + 1 divisors: 1, p, p_2, p_3, ..., p^k. Hence, d(p^k) = k + 1.

Let n = p^k q^l. Consider two sets: P ={1, p, p_2, p_3, ..., p_k} and Q = {1, q, q_2, q_3, ..., q_l}

Any divisor of the number p^k q^l can be represented in the form x \cdot y, where x \in P, y \in Q. A divisor from can be chosen in k + 1 ways, and a divisor from can be chosen in l + 1 ways. Therefore, a divisor d = x \cdot y can be formed in (k + 1) \cdot (l + 1) ways.

Decompose the number into its prime factors: n = p_1^{a_1}p_2^{a_2}...p_k^{a_k}. The number of divisors of is equal to

d(n) = (a_1 + 1) \cdot (a_2 + 1) \cdot ... \cdot (a_k + 1)

Example

The number n = 18 has divisors: 1, 2, 3, 6, 9, 18.

Let's decompose the number n = 18 into its prime factors:

18 = 2 \cdot 3^2

Therefore

d(18) = (1 + 1) \cdot (2 + 1) = 2 \cdot 3 = 6

Subtracting two divisors ( and ), we get the answer: divisors.

Algorithm implementation

The function CountDivisors decomposes the number into its prime factors and calculates the number of its divisors .

int CountDivisors(int n)
{
  int c, i, res = 1;
  for(i = 2; i * i <= n; i++)
  {
    if (n % i == 0)
    {
      c = 0;
      while(n % i == 0)
      {
        n /= i;
        c++;
      }
      res *= (c + 1);
    }
  }
  if (n > 1) res *= 2;
  return res;
}

The main part of the program. Read the value of .

scanf("%d",&n);

Calculate and print the answer. From the total number of divisors subtract two divisors: and the number itself.

printf("%d\n",CountDivisors(n)-2);

Python implementation

import math

The function CountDivisors decomposes the number into its prime factors and calculates the number of its divisors .

def CountDivisors(n):
  res = 1;
  for i in range(2, int(math.sqrt(n)) + 1):
    if (n % i == 0):
      c = 0
      while (n % i == 0):
        n //= i
        c += 1
      res *= (c + 1);
  if (n > 1): res *= 2;
  return res;

The main part of the program. Read the value of .

n = int(input())

Calculate and print the answer. From the total number of divisors subtract two divisors: and the number itself.

print(CountDivisors(n) - 2)