1. 程式人生 > >UVa 10061 - How many zero's and how many digits ?

UVa 10061 - How many zero's and how many digits ?

dig 原來 最大 mat 末尾 ont Language namespace pac

版權聲明:本文為博主原創文章。未經博主同意不得轉載。

https://blog.csdn.net/mobius_strip/article/details/32701577

題目:給你一個數字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組成的最大因子

? ? ? ? ? ? 這裏找到全部的,n的素因子的最大指數o = p^r。(p為素數。p^r < b < p^(r+1)),找到最小的解。

? ? ? ? ? ? {被劃掉的部分是原來的,錯的寫法,多謝HTT_H的的指正}

? ? ? ? ? ? 求位數註意不要用斯特林公式,精度有問題(⊙_⊙),直接地推打表計算。

說明:註意精度。

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>

#define min(a,b) (a)<(b)?

(a):(b) 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,Min; while ( cin >> n >> b ) { //計算base的最大質因數 mbase = 1,base = b,Min = -1; for ( int i = 2 ; i <= base ; ++ i ) { count = 0; while ( base%i == 0 ) { mbase = i; base /= i; count ++; } if ( count ) { if ( Min == -1 ) Min = f( n, mbase )/count; else Min = min( Min, f( n, mbase )/count ); } } cout << Min << " "; cout << int(dig[n]/log(b+0.0)+1e-8+1) << endl; } return 0; }



UVa 10061 - How many zero's and how many digits ?