题目:给你一个数字n,一个数字b,问n!转化成b进制后的位数和尾数的0的个数。
分析:数论。
末尾的0,当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 <iostream> #include <cstdlib> #include <cstdio> #include <cmath> using namespace std; double dig[1<<20]; int f( int n, int b ) { if ( n < b ) return 0; else return n/b + f( n/b, b ); } int main() { dig[0] = 0.0; for ( int i = 1 ; i < (1<<20) ; ++ i ) dig[i] = dig[i-1] + log(i+0.0); int b,n,mbase,base,count; while ( cin >> n >> b ) { //计算base的最大质因数 mbase = 1,base = b; for ( int i = 2 ; i <= base ; ++ i ) { count = 0; while ( base%i == 0 ) { mbase = i; base /= i; count ++; } } cout << f( n, mbase )/count << " "; cout << int(dig[n]/log(b+0.0)+1e-8+1) << endl; } return 0; }
UVa 10061 - How many zero's and how many digits ?,布布扣,bubuko.com
UVa 10061 - How many zero's and how many digits ?
原文:http://blog.csdn.net/mobius_strip/article/details/32701577