杭电1018 Big Number

来源:互联网 发布:类似皮影客的软件 编辑:程序博客网 时间:2024/06/10 22:42
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
21020
 

Sample Output
719
这题当初看题目的时候就挺懵逼,然后用Geogle翻译翻出来,发现是求输入的数的阶乘的位数,阶乘的话用递归就能实现,但是输入的数一大,大数相乘本来就很难实现,
而且结果会超出表示范围,long long也扛不住,怎么存储这些中间数据呢,还是懵逼qwq...然后就在discuss中了解到:任意一个正整数a的位数等于
(int)log10(a) + 1;为什么呢?下面给大家推导一下:
  对于任意一个给定的正整数a,  假设10^(x-1)<=a<10^x,那么显然a的位数为x位,  又因为  log10(10^(x-1))<=log10(a)<(log10(10^x))  即x-1<=log10(a)<x  则(int)log10(a)=x-1,  即(int)log10(a)+1=x  即a的位数是(int)log10(a)+1所以,在这个前提下,求n的阶乘的位数就变成了求(int)log10(n*(n-1)*(n-2)*(n-3)...*2*1)+1,又有log10(a*b)=log10(a)+log10(b),所以,该题就变成求
(int)(log10(n)+log10(n-1)+log10(n-2)+...+log10(2)+log10(1))+1,用for循环即可实现。
#include <iostream>#include <cmath>using namespace std;int main(){int n;cin>>n;int num;long double result; while(n--){result=0;cin>>num;for(int i=1;i<=num;i++){result+=(log10(i));}cout<<((int)result+1)<<endl;}return 0;} 
期间我还遇到一个问题:在for循环外我令result=(int)result+1;再输出result,结果就不对了,想了下,没想出来咋回事???
推荐大神博客·:http://blog.csdn.net/ld_1090815922/article/details/64248275

 
原创粉丝点击