TJU2848(Factorial )

 

2845.   Factorial
Time Limit: 1.0 Seconds   Memory Limit: 65536K
Total Runs: 1408   Accepted Runs: 411



Robby is a clever boy, he can do multiplication very quickly, even in base-2 (binary system), base-16 (hexadecimal system) or base-100000.

Now he wants to challenge your computer, the task is quite simple: Given a positive integer N, if we express the N ! (N ! = N * (N - 1) * (N - 2) * ... * 2 * 1) in base-B, how many ZEROs there will be at the end of the number. Can you make a wonderful program to beat him?

Input

Each test case contain one line with two numbers N and B. (1 ≤ N ≤ 109, 2 ≤ B ≤ 100000)

The input is terminated with N = B = 0.

Output

Output one line for each test case, indicating the number of ZEROs.

Sample Input

7 10
7 10000
7 2
0 0

 

Sample Output

1
0
4

 

Hint

7! = (5040)10, so there will be one zero at the end in base-10. But in base-10000, the number (5040)10 can be expressed in one non-zero digit, so the second answer is 0. In base-2, 7! = (1001110110000)2, so the third answer is 4.

Problem Setter: RoBa


/*
    2009-05-11 14:07:04 Accepted 2845 C++ 0.8K 0'00.00" 1204K 
*/

#include 
<iostream>
using namespace std;

int get_ans(int n, int b)
{
    
int sum = 0;

    
while(n / b)
    
{
        sum 
+= n / b;
        n 
/= b;
    }

    
return sum;
}


int get_small_ans(int n, int b)
{
    
bool flag = true;
    
int cnt, ans = 0;
    
int i;

    
for(i = 2; i * i <= b; i++)
    
{
        cnt 
= 0;
        
while(b % i == 0)
        
{//每次去进制的质因子
            b /= i;
            cnt
++;
        }


        
if(cnt)
        
{
            
if(flag)
            
{
                ans 
= get_ans(n, i) / cnt;
                flag 
= false;
            }

            
else //取进制质因子中的最小一个
                ans = min(ans, get_ans(n, i) / cnt);
        }


    }


    
if(b > 1)
    
{    
        
if(flag)
            ans 
= get_ans(n, b);
        
else
            ans 
= min(ans, get_ans(n, b));
    }

    
return ans;
}


int main()
{
    
int n, b;

    
while(scanf("%d%d"&n, &b) != EOF)
    
{
        
if(!&& !b)
            
break;
        printf(
"%d\n", get_small_ans(n, b));
    }

    
return 0;
}

posted on 2009-05-11 14:07  Xredman  阅读(196)  评论(0编辑  收藏  举报

导航