Problem 555
Trailing Zeros of N! in Base B
Hard · 30 pts · Math, Number Theory
Problem
Count the trailing zeros of N! (N factorial) when it is written in base B. That count is the largest k such that B^k divides N!. Factor B into primes, B = p1^e1 × p2^e2 × ..., and for each prime count how many times it divides N! with Legendre's formula: floor(N/p) + floor(N/p²) + .... The answer is the minimum over all primes of (that count divided by e, rounded down). The numbers in this problem can be larger than a 32-bit int can hold (about 2.1 × 10^9), so use a 64-bit integer type: long long in C++, long in Java (Python needs nothing special).
Input
A single line with two integers N and B.
Output
Print the number of trailing zeros of N! in base B.
Constraints
0 <= N <= 10^18; 2 <= B <= 10^6
Example input
5 2
Example output
3
Explanation
5! = 120, which is 1111000 in base 2, so it ends with 3 zeros. Legendre's formula agrees: floor(5/2) + floor(5/4) = 2 + 1 = 3 factors of 2.