light oj 1045

 light oj 1045

Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu

Description

Factorial of an integer is defined by the following function

f(0) = 1

f(n) = f(n - 1) * n, if(n > 0)

So, factorial of 5 is 120. But in different bases, the factorial may be different. For example, factorial of 5 in base 8 is 170.

In this problem, you have to find the number of digit(s) of the factorial of an integer in a certain base.

Input

Input starts with an integer T (≤ 50000), denoting the number of test cases.

Each case begins with two integers n (0 ≤ n ≤ 106) and base (2 ≤ base ≤ 1000). Both of these integers will be given in decimal.

Output

For each case of input you have to print the case number and the digit(s) of factorial n in the given base.

Sample Input

5

5 10

8 10

22 3

1000000 2

0 100

Sample Output

Case 1: 3

Case 2: 5

Case 3: 45

Case 4: 18488885

Case 5: 1


【題目分析】

     本題的大概題意是說,N是十進制的數,求N!在K進制下的位數。N的範圍雖然不大,才10^6,但是N!卻大得驚人。如果直接求N的階乘,轉化爲K進制的數再統計位數,理論上運用高精度算法行得通。但是時間只有2s,就肯定過不了。
     計算N!在K進制下的位數,即計算 [ log(1)+log(2)+...+log(N) ]+1  其中log的底數都是K。在此要先了解計算機是怎麼表示對數的。計算機的log默認爲自然對數,即以e爲底。   或者log10(a), 就是以10爲底,其他的都得通過換底公式來表示。

loga(b)=logc(b)/logc(a)




 N!在十進制下的位數就是  log10 ( N ! )  +1  ( 自己找個數驗證 ) ,N!在K進制下的位數就是  logK( N ! )  +1  ( K 爲底數 ),而計算機不能直接以K爲底求對數。所以運用換底公式, logK( N ! )  = log( K ) / log ( N!)   ,注意,等號右邊的 log 都是默認以e爲底。

正式進入解題了,題目給出N,K,如果每一次輸入N,K 都要計算 N!的話,那就有很大的開銷,開銷爲O(N)。
所以可以採取一種辦法,先預處理,用double數組 sum[ 1000000 ] 把 log ( N ! )  存起來。數組 應該夠的,需要說的是定義大數組儘量放到外面,這樣比較妥當,要不運行時會出錯。
用sum [ i ] 表示  log(1 )+log(2)+。。。+log(i) , 這樣時間開始時花費O(N),之後每次花費O(1),等輸入的時候用換底公式處理一下就得到答案了。

原作地址

AC代碼:

#include <cstdio>
#include <cmath>
#include <string.h>
using namespace std;
double sum[1000008];
int main()
{
    double res;
    int Case, n, a, i;
    int num = 1;
    memset(sum, 0, sizeof(sum));
    for(i = 1; i < 1000008; i++)
        sum[i] = sum[i-1]+log(i);
    scanf("%d", &Case);
    while(Case--)
    {
        scanf("%d %d", &n, &a);
        if(n == 0) printf("Case %d: 1\n", num++);
        else
        {
            res = sum[n];
            res = res/log(a)+1;
            printf("Case %d: %d\n", num++, (int)res);
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章