Given two numbers n and k find the greatest power of k that divides n!

Writing the factorial expression explicitely

n!=1β‹…2β‹…3…(nβˆ’1)β‹…n

We can see that every k-th member of the factorial is divisible by k therefore one answer is ⌊nkβŒ‹, however we can also see that every k2-th term is also divisible by k two times and it gives one more term to the answer, that is ⌊nk2βŒ‹, which means that every ki-th term adds one factor to the answer, thus the answer is

⌊nkβŒ‹+⌊nk2βŒ‹+…+⌊nkiβŒ‹+…

The sum is actually finite and the maximum value of i can be found using logarithms, let ki>n, applying logarithms we have iβ‹…log(k)>log(n) which is equal to i>log(n)log(k) which is the same as i>logkn

The sum discovered by Adrien-Marie Legendre is called Legendre’s Formula , let da(b) be the number of times a divides b

dk(n!)=βˆ‘i=1logkn⌊nkiβŒ‹
/**
 * Computes the maximum power of `k` that is a divisor of `n!`
 *
 * @param {int} n
 * @param {int} k
 * @return {int}
 */
int max_power_in_factorial(int n, int k) {
  int ans = 0;
  while (n) {
    n /= k;
    ans += n;
  }
  return ans;
}