![]() |
VOOZH | about |
Given an integer n and a prime number p, the task is to find the largest x such that px (p raised to power x) divides n!.
Examples:
Input: n = 7, p = 3
Output: x = 2
Explanation: 32 divides 7! and 2 is the largest such power of 3.Input: n = 10, p = 3
Output: x = 4
Explanation: 34 divides 10! and 4 is the largest such power of 3.
Table of Content
We know that n! is the product of all the integers from 1 to n. For each multiple of p in the range [1, n], we know that we get at least one factor of p. Therefore in n!, there are at least floor(n!/p) integers divisible by p. Furthermore, for each multiple of p2, we get one more factor of p. Similarly, for each multiple of p3, we get another extra factor of p. So, the largest value of x is the sum of total number of factors, that is floor(n/p) + floor(n/p2) + floor(n/p3) ... and so on till the floor value reaches 0.
Legendre's Formula:
Largest exponent of p in n! = Sum of (floor(n/(pi)), where i = 1, 2, 3, 4..... and so on.
4
Time complexity: O(logpn), as in each iteration we are reducing n to n/p.
Auxiliary Space: O(1)
Since we are repeatedly counting the factors of p and keep reducing the value of n, we can also use recursion to solve the problem. The recurrence relation will be:
largestPower(n, p) = n/p + largestPower(n/p, p)
The base case will be when n = 0, we can return the count of factors as 0.
4
Time complexity: O(logpn), as in each recursive call we are reducing n to n/p.
Auxiliary Space: O(logpn), as we are using recursive call stack.