Open in App
Not now

Find maximum power of a number that divides a factorial

Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact).

Examples:

```Input :
fact = 5, n = 2
Output :
3
Explanation:
Value of 5! is 120. The largest power
of 2 that divides 120 is 8 (or 23

Input :
fact = 146, n = 15
Output :
35```

The idea is based on Legendreâ€™s formula which finds largest power of a prime number that divides fact!. We find all prime factors of n. For every prime factor we find largest power of it that divides fact!. Finally we return minimum of all found powers.

Illustration :

```fact = 146, n=15
First find the prime factor of 15 that are 3
and 5 then first divide with 3 and add i.e.

Applying Legendreâ€™s formula for prime
factor 3.
[146/3]+[48/3]+[16/3]+[5/3]+[1/3] = 70
48  +   16  +  5  +  1  +  0   = 70
There is 70 is maximum power of 3 prime number.
146! is divisible by 3^70 which is maximum.

Applying Legendreâ€™s formula for prime
factor 5.
[146/5]+[29/5]+[5/5]+[1/5] = 35
29  +   5  +  1  +  0   = 35
There is 35 is maximum power of 5 prime
number.```

Minimum of two powers is 35 which is our answer.
Note : If multiple powers of a prime factor are present in n, then we divide the count to get the maximum power value for this factor.

Below is the implementation of the above approach:

C++

 `// CPP program to find largest power of` `// a number (which may be composite) that` `// divides factorial.` `#include ` `using` `namespace` `std;`   `// for find maximum power of prime number` `// p which can divide fact number` `int` `findPowerPrime(``int` `fact, ``int` `p)` `{` `    ``int` `res = 0;` `    ``while` `(fact > 0) {` `        ``res += fact / p;` `        ``fact /= p;` `    ``}`   `    ``return` `res;` `}`   `// Returns sum of all factors of n.` `int` `findPowerComposite(``int` `fact, ``int` `n)` `{` `    ``// To store result (minimum power of a` `    ``// prime factor that divides fact! )` `    ``int` `res = INT_MAX;`   `    ``// Traverse through all prime factors` `    ``// of n.` `    ``for` `(``int` `i = 2; i <= ``sqrt``(n); i++) {`   `        ``// counter for count the` `        ``// power of prime number` `        ``int` `count = 0;` `        ``while` `(n % i == 0) {` `            ``count++;` `            ``n = n / i;` `        ``}`   `        ``if` `(count > 0) {`   `            ``// Maximum power of i that divides` `            ``// fact!. We divide by count to handle` `            ``// multiple occurrences of a prime factor.` `            ``int` `curr_pow = findPowerPrime(fact, i) / count;` `            ``res = min(res, curr_pow);` `        ``}` `    ``}`   `    ``// This condition is to handle` `    ``// the case when n is a prime` `    ``// number greater than 2.` `    ``if` `(n >= 2) {` `        ``int` `curr_pow = findPowerPrime(fact, n);` `        ``res = min(res, curr_pow);` `    ``}`   `    ``return` `res;` `}`   `// Driver code` `int` `main()` `{` `    ``int` `fact = 146, n = 5;` `    `  `    ``// Function Call` `    ``cout << findPowerComposite(fact, n);` `    ``return` `0;` `}`

Java

 `// Java program to find largest power of` `// a number (which may be composite) that` `// divides factorial.` `class` `GFG {`   `    ``// for find maximum power of prime number` `    ``// p which can divide fact number` `    ``static` `int` `findPowerPrime(``int` `fact, ``int` `p)` `    ``{` `        ``int` `res = ``0``;` `        ``while` `(fact > ``0``) {` `            ``res += fact / p;` `            ``fact /= p;` `        ``}`   `        ``return` `res;` `    ``}`   `    ``// Returns sum of all factors of n.` `    ``static` `int` `findPowerComposite(``int` `fact, ``int` `n)` `    ``{` `      `  `        ``// To store result (minimum power of a` `        ``// prime factor that divides fact! )` `        ``int` `res = Integer.MAX_VALUE;`   `        ``// Traverse through all prime factors` `        ``// of n.` `        ``for` `(``int` `i = ``2``; i <= Math.sqrt(n); i++) ` `        ``{`   `            ``// counter for count the` `            ``// power of prime number` `            ``int` `count = ``0``;` `            ``if` `(n % i == ``0``)` `            ``{` `                ``count++;` `                ``n = n / i;` `            ``}`   `            ``if` `(count > ``0``)` `            ``{`   `                ``// Maximum power of i that divides` `                ``// fact!. We divide by count to` `                ``// handle multiple occurrences of` `                ``// a prime factor.` `                ``int` `curr_pow` `                    ``= findPowerPrime(fact, i) / count;` `                ``res = Math.min(res, curr_pow);` `            ``}` `        ``}`   `        ``// This condition is to handle` `        ``// the case when n is a prime` `        ``// number greater than 2.` `        ``if` `(n >= ``2``) {` `            ``int` `curr_pow = findPowerPrime(fact, n);` `            ``res = Math.min(res, curr_pow);` `        ``}`   `        ``return` `res;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `fact = ``146``, n = ``5``;` `      `  `        ``// Function Call` `        ``System.out.println(findPowerComposite(fact, n));` `    ``}` `}`   `// This code is contributed by prerna saini`

Python3

 `# Python program to find largest power of` `# a number (which may be composite) that` `# divides factorial.` `import` `math`   `# For find maximum power of prime number` `# p which can divide fact number`     `def` `findPowerPrime(fact, p):` `    ``res ``=` `0` `    ``while` `fact:` `        ``res ``+``=` `fact ``/``/` `p` `        ``fact ``/``/``=` `p`   `    ``return` `res`   `# Returns sum of all factors of n`     `def` `findPowerComposite(fact, n):`   `    ``# To store result (minimum power of a` `    ``# prime factor that divides fact! )` `    ``res ``=` `math.inf`   `    ``# Traverse through all prime factors` `    ``# of n.` `    ``for` `i ``in` `range``(``2``, ``int``(n``*``*``0.5``) ``+` `1``):`   `        ``# Counter for count the` `        ``# power of prime number` `        ``count ``=` `0` `        ``if` `not` `n ``%` `i:` `            ``count ``+``=` `1` `            ``n ``=` `n ``/``/` `i`   `        ``if` `count:`   `            ``# Maximum power of i that divides` `            ``# fact!. We divide by count to handle` `            ``# multiple occurrences of a prime factor.` `            ``curr_pow ``=` `findPowerPrime(fact, i) ``/``/` `count` `            ``res ``=` `min``(res, curr_pow)`   `    ``# This condition is to handle` `    ``# the case when n is a prime` `    ``# number greater than 2.` `    ``if` `n >``=` `2``:` `        ``curr_pow ``=` `findPowerPrime(fact, n)` `        ``res ``=` `min``(res, curr_pow)`   `    ``return` `res`     `# Driver code` `fact ``=` `146` `n ``=` `5`   `# Function Call` `print``(findPowerComposite(fact, n))`     `# This code is contributed by Ansu Kumari`

C#

 `// C# program to find largest power of` `// a number (which may be composite) that` `// divides factorial.` `using` `System;`   `class` `GFG {`   `    ``// for find maximum power of prime number` `    ``// p which can divide fact number` `    ``static` `int` `findPowerPrime(``int` `fact, ``int` `p)` `    ``{` `        ``int` `res = 0;` `        ``while` `(fact > 0) {` `            ``res += fact / p;` `            ``fact /= p;` `        ``}`   `        ``return` `res;` `    ``}`   `    ``// Returns sum of all factors of n.` `    ``static` `int` `findPowerComposite(``int` `fact, ``int` `n)` `    ``{` `        ``// To store result (minimum power of a` `        ``// prime factor that divides fact! )` `        ``int` `res = ``int``.MaxValue;`   `        ``// Traverse through all prime factors` `        ``// of n.` `        ``for` `(``int` `i = 2; i <= Math.Sqrt(n); i++) {`   `            ``// counter for count the` `            ``// power of prime number` `            ``int` `count = 0;` `            ``if` `(n % i == 0) {` `                ``count++;` `                ``n = n / i;` `            ``}`   `            ``if` `(count > 0) {`   `                ``// Maximum power of i that divides` `                ``// fact!. We divide by count to` `                ``// handle multiple occurrences of` `                ``// a prime factor.` `                ``int` `curr_pow` `                    ``= findPowerPrime(fact, i) / count;` `                ``res = Math.Min(res, curr_pow);` `            ``}` `        ``}`   `        ``// This condition is to handle` `        ``// the case when n is a prime` `        ``// number greater than 2.` `        ``if` `(n >= 2) {` `            ``int` `curr_pow = findPowerPrime(fact, n);` `            ``res = Math.Min(res, curr_pow);` `        ``}`   `        ``return` `res;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main()` `    ``{` `        ``int` `fact = 146, n = 5;` `      `  `        ``// Function Call` `        ``Console.WriteLine(findPowerComposite(fact, n));` `    ``}` `}` `// This code is contributed by vt_m`

PHP

 ` 0) ` `    ``{        ` `        ``\$res` `+= ``intval``(``\$fact` `/ ``\$p``);` `        ``\$fact` `= ``intval``(``\$fact` `/ ``\$p``);` `    ``} ` `    ``return` `\$res``;` `}` `  `  `// Returns sum of` `// all factors of n.` `function` `findPowerComposite(``\$fact``, ``\$n``)` `{` `    ``// To store result (minimum ` `    ``// power of a prime factor ` `    ``// that divides fact! )` `    ``\$res` `= PHP_INT_MAX;` `  `  `    ``// Traverse through all ` `    ``// prime factors of n.` `    ``for` `(``\$i` `= 2;` `         ``\$i` `<= sqrt(``\$n``); ``\$i``++) ` `    ``{        ` `  `  `        ``// counter for count the` `        ``// power of prime number` `        ``\$count` `= 0;` `        ``if` `(``\$n` `% ``\$i` `== 0)` `        ``{` `            ``\$count``++;` `            ``\$n` `= ``intval``(``\$n` `/ ``\$i``);` `        ``}` `  `  `        ``if` `(``\$count` `> 0) ` `        ``{` `  `  `            ``// Maximum power of i ` `            ``// that divides fact!. ` `            ``// We divide by count ` `            ``// to handle multiple ` `            ``// occurrences of a` `            ``// prime factor.` `            ``\$curr_pow` `= ``intval``(findPowerPrime(` `                               ``\$fact``, ``\$i``) / ``\$count``);` `            ``\$res` `= min(``\$res``, ``\$curr_pow``);` `         ``}` `    ``}` `  `  `    ``// This condition is to` `    ``// handle the case when ` `    ``// n is a prime number ` `    ``// greater than 2.` `    ``if` `(``\$n` `>= 2)` `    ``{` `        ``\$curr_pow`  `= findPowerPrime(``\$fact``, ``\$n``);` `        ``\$res` `= min(``\$res``, ``\$curr_pow``);` `    ``}` `    ``return` `\$res``;` `}` `  `  `// Driver code` `\$fact` `= 146; ``\$n` `= 5;`   `// Function Call` `echo` `(findPowerComposite(``\$fact``, ``\$n``));`   `// This code is contributed by ` `// Manish Shaw(manishshaw1)` `?>`

Javascript

 ``

Output

`35`

Time Complexity: O(sqrt(n)*log(n))
Auxiliary Space: O(1), as no extra space is used

Approach 2 :- We can represent a number n as a product of its prime factors, such as:

n = p1^a1 * p2^a2 * … * pk^ak

where p1, p2, …, pk are distinct prime numbers and a1, a2, …, ak are non-negative integers.

Then, the maximum power of a number p that divides n! is the sum of the quotients of n divided by successive powers of p, up to the largest power of p that divides n. More formally, we can write:

max_power = floor(n/p) + floor(n/p^2) + floor(n/p^3) + … + floor(n/p^k)

where k is the largest integer such that p^k divides n.

Here, we first read in the values of n and p. Then, we initialize the maximum power to 0 and the power of p to pk = p. We iterate over all powers of p that are less than or equal to n, and at each iteration, we add floor(n/pk) to the maximum power and multiply pk by p. Finally, we output the result.

This approach is similar to the first approach but is based on prime factorization instead of iterating over all possible divisors. It is more efficient for large values of n and p.

C++

 `#include ` `#include ` `using` `namespace` `std;`   `int` `main() {` `    ``int` `n=146, p=5;` `    `    `    ``int` `max_power = 0;` `    ``int` `pk = p;` `    ``while` `(pk <= n) {` `        ``max_power += n/pk;` `        ``pk *= p;` `    ``}`   `    ``cout << max_power << endl;`   `    ``return` `0;` `}`

Output

```35
```

Time Complexity: O(log_p(n))

The time complexity of the above approach is O(log_p(n)), where p is the given number and n is the factorial whose maximum power of p is to be found. This is because we are dividing n by increasing powers of p until we reach the largest power of p that divides n, and the number of divisions required is proportional to log_p(n).

Auxiliary Space: O(1)

The space complexity of the above approach is O(1), as we are only using a constant amount of extra memory to store the variables used in the computation. Specifically, we only need to store the values of n, p, max_power, and pk, which are all integers and require a constant amount of memory.

My Personal Notes arrow_drop_up
Related Articles