How many zeros and how many digits?
Input: standard input
Output: standard output
Given a decimal integer number you will have to find out how many trailing zeros will be there in its factorial in a given number system and also you will have to find how many digits will its factorial have in a given number system? You can assume that for a b based number system there are b different symbols to denote values ranging from 0 ... b-1.
Input
There will be several lines of input. Each line makes a block. Each line will contain a decimal number N (a 20bit unsigned number) and a decimal number B (1<B<=800), which is the base of the number system you have to consider. As for example 5! = 120 (in decimal) but it is 78 in hexadecimal number system. So in Hexadecimal 5! has no trailing zeros
Output
For each line of input output in a single line how many trailing zeros will the factorial of that number have in the given number system and also how many digits will the factorial of that number have in that given number system. Separate these two numbers with a single space. You can be sure that the number of trailing zeros or the number of digits will not be greater than 2^31-1
Sample Input:
2 10
5 16
5 10
Sample Output:
0 10 2
1 3
解决方案:
1)多少个不是0的位数,可用log函数。a1*a2*a3*a4...*an<=base^k;对两边求对数:log(a1*a2*a3*a4...*an)<=k*log(base);
k<=[log(a1)+log(a2)+...+log(an)]/log(base)=sum;最后,由于log的精度问题,应该这样处理:sum=ceil(sum+1e-9);
2)将base分解质因数,对a1*a2*a3*a4...*an也分解质因数,看其包含多少个base的质因数,就是0的个数。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#define nmax 10050
using namespace std;
int num[nmax];
int getbit(int nn,int bb)
{
double sum=0.0;
for(int i=1;i<=nn;i++)
sum+=log(i);
int s=ceil(sum/log(bb)+1e-9);//对精度的处理
return s;
}
int getzero(int nn,int bb)
{
memset(num,0,sizeof(num));
for(int i=2;i<=nn;i++)
{ int g=i;
for(int j=2;j<=g&&j<=bb;j++)
{
while(g%j==0)
{
num[j]++;
g/=j;
}
}
}//对阶乘分解质因数
int cnt=0;
for(;;)
{
int g=bb;
for(int i=2;i<=bb;i++)
{
while(g%i==0)
{
if(num[i]>0)
num[i]--;
else goto out;
g=g/i;
}
}
cnt++;//计算0的个数
// cout<<cnt<<endl;
}
out: return cnt;
}
int main()
{
int n,b;
while(~scanf("%d%d",&n,&b))//tle了几次,发现是忘了设置文件输入结束的条件了。
{
int aa=getbit(n,b);
int bb=getzero(n,b);
printf("%d %d\n",bb,aa);
}
return 0;
}