Given two numbers k and n, find the largest power of k that divides n!
K > 1
Input : n = 7, k = 2 Output : 4 Explanation : 7! = 5040 The largest power of 2 that divides 5040 is 24. Input : n = 10, k = 9 Output : 2 The largest power of 9 that divides 10! is 92.
We have discussed a solution in below post when k is always prime.
Now to find the power of any non-prime number k in n!, we first find all the prime factors of the number k along with the count of number of their occurrences. Then for each prime factor, we count occurrences using Legendre’s formula which states that the largest possible power of a prime number p in n is ⌊n/p⌋ + ⌊n/(p2)⌋ + ⌊n/(p3)⌋ + ……
Over all the prime factors p of K, the one with the minimum value of findPowerOfK(n, p)/count will be our answer where count is number of occurrences of p in k.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.