Factorial Problem in Base K(zoj3621)

Factorial Problem in Base K

Time Limit: 2 Seconds Memory Limit: 65536 KB

How many zeros are there in the end of s! if both s and s! are written in base k which is not necessarily to be 10? For general base, the digit order is 0-9,A-Z,a-z(increasingly), for example F4 in base 46 is actually 694 in base 10,and f4 in base 46 is 1890 in base 10.

Input

There are multiple cases(less than 10000). Each case is a line containing two integers s and k(0 ≤ s < 2^63, 2 ≤ k ≤ 62).

Output

For each case, output a single line containing exactly one integer in base 10 indicating the number of zeros in the end of s!.

Sample Input

101 2
12 7

Sample Output

3
1

题意:给你s和k表示k进制的s;现在求s的10进制的阶乘换成k进制后末尾有几个0;

思路:找k进制的质因子个数kv[i],以及s的阶乘中质因子的个数pn,那么最后换成k进制后有多少个0,就是pn/kv[i]中最小的。

刚开始找出来pn的时候,测试数据都过了,可是WA了,,,,后来我把ans开很大很大,结果就过了。郁闷

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#define N 65
using namespace std;
char str[N];
int k;
long long s;
int prm[20]= {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61},kv[20];
/*
int judge(int x,int tp)
{
    int y=x,a=0;
    while(y<=tp)
    {

        a+=tp/y;
//        printf("y:%d	temp:%d     ans:%d
",y,temp,ans);
        if(tp/y<x)
            break;
        y*=x;
    }
    return a;
}*/
void solve(long long x)
{
    int i;
    long long res,ans=0x7ffffffffffffff;//开小了,,居然WA
    long long pn;
    for(i=0; i<18; i++)
    {
        res=x;
        res=res/prm[i];
        pn=res;
        while(res)
        {
            res=res/prm[i];
            pn+=res;
        }
        if(kv[i]&&pn/kv[i]<ans) ans=pn/kv[i];
    }
    printf("%lld
",ans);
}
int main()
{
    int i,j;
    while(scanf("%s%d",str,&k)!=EOF)
    {
        int len=strlen(str);
        s=0;
        for(i=0; i<len; i++)
        {
            int num;
            if(str[i]<='z'&&str[i]>='a')
                num=str[i]-'a'+36;
            else if(str[i]<='Z'&&str[i]>= 'A')
                num=str[i]-'A'+10;
            else
                num=str[i]-'0';
            s=num+s*k;
        }
        memset(kv,0,sizeof(kv));
        int n=k,x;
        for(i=0; i<18; i++)
        {
            while(n%prm[i]==0)
            {
                kv[i]++;
                n/=prm[i];
            }
        }
        solve(s);
    }
    return 0;
}
记得以前也做过类似的题。就是求阶乘中含多少质因子的题目。



原文地址:https://www.cnblogs.com/yuyixingkong/p/3945337.html