程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> uva 10061 How many zeros and how many digits ?

uva 10061 How many zeros and how many digits ?

編輯:C++入門知識

 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進制m的位數和後面0的個數。

解題思路:1,求位數:當base為10時,10^(m-1) < n < 10 ^m,兩邊同去log10,m - 1 < log10(n) < m,n 的位數為(m-1).

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;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved