![]() |
VOOZH | about |
Given two positive integers k and n, where k > 1, find the largest power of k that divides n! (n factorial).
Examples:
Input: n = 7, k = 2
Output: 4
Explanation: 7! = 5040, and 2^4 = 16 is the highest power of 2 that divides 5040.Input: n = 10, k = 9
Output: 2
Explanation: 10! = 3628800, and 9^2 = 81 is the highest power of 9 that divides 3628800.
Table of Content
This approach first computes n! explicitly, then repeatedly divides it by k to count how many times k divides n!.
Note: This approach does not work for large values of n, because computing n! directly causes integer overflow.
Factorials grow very rapidly, and for even moderately large n (e.g., n > 20), the value of n! can exceed the range of standard data types.
2
Factorize k into its prime components, then for each prime, naively count its total occurrences in n! by checking every number from 1 to n.
Finally, compute how many times k can divide n! by dividing the total count by the prime’s exponent in k.
Step By Step Implementations
2
Time Complexity: O(√k + m × n log n), O(√k) for factorization and O(m × n log n) for counting divisions, where m is the number of prime factors of k (m is nearly equal to log k).
Auxiliary Space: O(log k) for unique prime factors the factors of k.
When p is a prime number, we can use Legendre’s formula to find the highest power of p that divides n!. The formula calculates this power as:
Since k may not be a prime number, we begin by factorizing it into its prime components, along with their respective exponents. For each prime factor p, we apply Legendre’s formula to calculate how many times p appears in the factorization of n!. We then divide this count by the exponent of p in k. The minimum of these values across all prime factors gives the largest power of k that divides n!
Step by step approach:
k into its prime factors along with their exponents.p in the factorization, calculate how many times p appears in the factorization of n! using:p in n! by its exponent in k to find how many times this prime allows k to divide n!kx such that kx divides n!2
Time Complexity: O(√k + m * log n), where m is number of distinct prime factors in k, O(√k) for prime factorization of k and log n for apply Legendre formula for each prime factor of k.
Auxiliary Space: O(m), where m is number of distinct prime factors in