Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact).
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.
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:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the last digit when factorial of A divides factorial of B
- Find two co-prime integers such that the first divides A and the second divides B
- Count of triplets (a, b, c) in the Array such that a divides b and b divides c
- Highest power of a number that divides other number
- Highest power of 2 that divides a number represented in binary
- Count of pairs in an array such that the highest power of 2 that divides their product is 1
- Highest power of 2 that divides the LCM of first N Natural numbers.
- Number of digits in N factorial to the power N
- Find a number that divides maximum array elements
- Find integers that divides maximum number of elements of the array
- Largest power of k in n! (factorial) where k may not be prime
- Find power of power under mod of a prime
- Find the sum of power of bit count raised to the power B
- Check if given number is a power of d where d is a power of 2
- Find the largest composite number that divides N but is strictly lesser than N
- Find the Smallest number that divides X^X
- Check if a M-th fibonacci number divides N-th fibonacci number
- Count of prime digits of a Number which divides the number
- Maximum number with same digit factorial product
- Compute power of power k times % m
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.