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
题目大意:
给你一个数字n,一个数字b,问n! 转化成b进制后的位数和尾数的0的个数。
解题思路:
1.求位数:
当base = 10时,10^(m-1) < n < 10 ^m,两边同去log10,m - 1 < log10(n) < m,n 的位数为(m-1).
<1> log10(a * b) = log10(a) + log10(b)。
<2> logb(a) = log c(a) / log c(b)转换进制位数。
<3> 浮点数的精度问题,求位数需要用到log函数,log函数的计算精度有误差。所以 最后需要对和加一个1e-9再floor才能过。
2.求末尾的0
当base = 10时,有公式 f(n)= f(n/5)+ n/5;
证明:
令k = n/5 则 n! = 5k * 5(k-1) * ... * 10 * 5 * a = 5^k * k! * a (a为不能整除5的部分)
即 f(n) = k + f(k) = n/5 + f( n/5 ) ( f(0) = 0 )
类似可推导 f( n, b ) = f( n/o ) + n/o,o为b的最大质因子p组成的最大因子 (p^r < b)
#include <stdio.h>
#include <math.h>
int count_digit(int n,int b) {
double sum = 0;
for(int i=1;i<=n;i++) {
sum += log((double)i);
}
sum = sum/log((double)b);
return floor(sum + 1e-9)+1;
}
int count_zero(int n,int b) {
int cnt1,cnt2;
int maxprime;
for(int i = 2; i <= b; i++) {
cnt1 = 0;
while(b % i == 0) { //计算出进制中最大的素数,并算出最大素数的个数
maxprime = i;
cnt1++;
b /= i;
}
}
cnt2 = 0;
for(int i = maxprime; i <= n; i *= maxprime) {
cnt2 += (n/i)/cnt1;
}
return cnt2;
}
int main() {
int n,b;
while( scanf("%d%d",&n,&b) != EOF ) {
int digit = count_digit(n,b);
int zero = count_zero(n,b);
printf("%d %d\n",zero,digit);
}
return 0;
}