杭电OJ:1018

杭电OJ:1018
Big Number

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 29468 Accepted Submission(s): 13518

Problem Description
In many applications very large integers numbers are required. Some of these applications are using keys for secure transmission of data, encryption, etc. In this problem you are given a number, you have to determine the number of digits in the factorial of the number.

Input
Input consists of several lines of integer numbers. The first line contains an integer n, which is the number of cases to be tested, followed by n lines, one integer 1 ≤ n ≤ 107 on each line.

Output
The output contains the number of digits in the factorial of the integers appearing in the input.

Sample Input
2
10
20

Sample Output
7
19

Source
Asia 2002, Dhaka (Bengal)

题意:求一个大整数阶乘的十进制数有多少位,既lg(N!)
这里做如下分解:
lg(N!) = lg(N(N-1)!) = lg(N) + lg((N-1)!) 则:
lg(N!) = lg(N) + lg(N-1) + … + lg(1)

同理,如果求该数的m进制数有多少位,也能变换为:
logm(N!) = logm(N) + logm(N-1) + … + logm(1)

GCC实现:

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

/** calculate the number of digits in the factorial of the given integers N */
int digits_of_factorial(int n){
    double num_dou = 0.;
    int i = 1;
    if( n <= 0){
        return 0;
    }
    for(; i<=n; i++){
        num_dou += log10((double)i);
    }
    return (int)num_dou + 1;
}

int main()
{
    int test_num = 0;
    int num = 0;
    int i = 0;

    scanf("%d", &test_num);
    for(; i<test_num; i++){
        scanf("%d", &num);
        printf("%d\n", digits_of_factorial(num));
    }
    return 0;
}

20150417更新
今天想到一个类似的问题:求N!的10进制数末尾有多少个0?
咋一看问题貌似挺复杂,实际上想想0是怎么产生的,该问题就容易解决了。

N!结果中0的产生:
0的产生莫非就是和10相乘,由于在计算N!的过程中多次和偶数相乘,那么N!计算结果中的0来自于和5相乘,因此结果中0的个数,就是
N*(N-1)*…*1中5的个数,所以该问题结果就是:

N/5

你可能感兴趣的:(数学,ACM,水题)