Related: Zeroes at the end of a factorial
Today, we are going to calculate how many zeroes are there at the end of \$n!\$ (the factorial of \$n\$) in base \$m\$.
Or in other words: For given integers \$n\$, and, \$m\$. Calculate the integer \$p\$ which is the highest power of \$m\$ dividing \$n!\$: \$p \in \mathbb{N}_0\$ which holds \$ \left( m^p \mid n! \right) \land \left( m^{p+1} \nmid n! \right) \$. Here, \$n!\$ is the factorial of \$n\$ which equals to the product of all positive integers less than or equal to \$n\$. The value of \$0!\$ is \$1\$.
Input / Output
- Two integers \$n\$, \$m\$.
- One integer: How many zeroes at end of \$n!\$ in base \$m\$.
Rules
- As code-golf, the shortest codes in bytes win.
- Your program is required to support \$0\le n\le 1{,}000{,}000\$; \$2\le m\le 1{,}000\$ at least. The program should be able to output correct results for any inputs in above range with reasonable resource (typically, <1 minutes on a normal laptop).
- As this question is only talking about integers. No floating point errors may allowed in your output. You may, however, output 3.0 when 3 is required. But 2.9999999999999996 is certainly not allowed.
Testcases
n, m -> output
0, 2 -> 0
1, 2 -> 0
2, 2 -> 1
3, 2 -> 1
4, 2 -> 3
9, 6 -> 4
10, 100 -> 1
80, 100 -> 9
4, 8 -> 1
15, 12 -> 5
16, 12 -> 6
39, 45 -> 8
100, 2 -> 97
100, 3 -> 48
100, 4 -> 48
100, 5 -> 24
100, 6 -> 48
100, 7 -> 16
100, 8 -> 32
100, 9 -> 24
100, 10 -> 24
100, 13 -> 7
100, 36 -> 24
100, 42 -> 16
100, 97 -> 1
100, 100 -> 12
1000000, 2 -> 999993
1000000, 3 -> 499993
1000000, 4 -> 499996
1000000, 6 -> 499993
1000000, 7 -> 166664
1000000, 8 -> 333331
1000000, 9 -> 249996
1000000, 999 -> 27776
1000000, 1000 -> 83332
Above \$n\$ is written in base 10. You are allowed to receive \$n\$ as an array of integers in base \$m\$ if you want.
Related OEIS
It is interesting that this question involve at least 14 sequences on OEIS. Maybe you can find out some helpful formula to solve this problem on it.
OEIS includes sequences for every \$2 \le m \le 16\$:
- 2: A011371
- 3, 6: A054861
- 4: A090616
- 5, 10, 15: A027868
- 7, 14: A054896
- 8: A090617
- 9: A090618
- 11: A064458
- 12: A090619
- 13: A090620
- 16: A090621
Also, by treating above sequences as a matrix, there are other related sequences: