uva 10061 How many zero's and how many digits ?(在bas进制下分解因子)

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 bbased 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 1
0 2
1 3

题目大意:求n!的bas进制的位数和后面0的个数。

解题思路:1,求位数:当base为10时,10^(m-1) < n < 10 ^m,两边同去log10,m - 1 < log10(n) < m,n 的位数为m.

PS:<1>log10(a * b) = log10(a) + log10(b)        求n!的位数时。

<2>logb(a) = log c(a) / log c(b)转换进制位数。

<3>浮点数的精度问题,求位数需要用到log函数,log函数的计算精度有误差。所以 最后需要对和加一个1e-9再floor才能过。

2,将n!分解成质因子,储存在数组里面,在对bas做多次分解,直到数组中的元素小于0.

#include<stdio.h>
#include<string.h>
#include<math.h>

#define N 10000
int num[N];

int count_digit(int n, int bas){
	double sum = 0;
	for (int i = 1; i <= n; i++)
		sum += log10(i);
	sum = sum / log10(bas);
	return floor(sum + 1e-9) + 1;
}

int count_zore(int n, int bas){
	memset(num, 0, sizeof(num));

	for (int i = 2; i <= n; i++){
		int g = i;
		for (int j = 2; j <= g && j <= bas; j++){
			while (g % j == 0){
				num[j]++;
				g = g / j;
			}
		}
	}

	int cnt = 0;

	while (1){
		int g = bas;

		for (int j = 2; j <= bas; j++){
			while (g % j == 0){
				if (num[j] > 0)
					num[j]--;
				else
					goto out;
				g = g / j;
			}
		}
		cnt++;
	}
out:
	return cnt;
}

int main(){
	int n, bas;
	while (scanf("%d%d", &n, &bas) != EOF){
		int ndigit = count_digit(n, bas);
		int nzore = count_zore(n, bas);
		printf("%d %d\n", nzore, ndigit);
	}
	return 0;
}

你可能感兴趣的:(uva 10061 How many zero's and how many digits ?(在bas进制下分解因子))