VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-divisors-of-factorial/

⇱ Count Divisors of Factorial - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Divisors of Factorial

Last Updated : 23 Jul, 2025

Given a number n, count the total number of divisors of n!.

Examples:

Input : n = 4
Output: 8
Explanation:
4! is 24. Divisors of 24 are 1, 2, 3, 4, 6,
8, 12 and 24.

Input : n = 5
Output : 16
Explanation:
5! is 120. Divisors of 120 are 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24 30, 40, 60 and 12 

A Simple Solution is to first compute the factorial of the given number, then count the number of divisors of the factorial. This solution is not efficient and may cause overflow due to factorial computation.
A better solution is based on Legendre’s formula. Below are the step:

  1. Find all prime numbers less than or equal to n (input number). We can use Sieve Algorithm for this. Let n be 6. All prime numbers less than 6 are {2, 3, 5}.
  2. For each prime number, p find the largest power of it that divides n!. We use Legendre’s formula for this purpose. 
    The value of largest power that divides n! is ?n/p? + ?n/(p2)? + ?n/(p3)? + ...... 
    Let these values be exp1, exp2, exp3,... Using the above formula, we get the below values for n = 6.
    • The largest power of 2 that divides 6!, exp1 = 4.
    • The largest power of 3 that divides 6!, exp2 = 2.
    • The largest power of 5 that divides 6!, exp3 = 1.
  3. The result is (exp1 + 1) * (exp2 + 1) * (exp3 + 1) ... for all prime numbers, For n = 6, the values exp1, exp2, and exp3 are 4 2 and 1 respectively (computed in above step 2). So our result is (4 + 1)*(2 + 1) * (1 + 1) = 30

Below is the implementation of the above idea. 


Output
30

Time Complexity: (O(n * log(logn))

Auxiliary Space: O(n)

This article is reviewed by team GeeksforGeeks.

Comment