杭电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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值