hdu 1018:Big Number(水题)

Big Number

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


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
 
Recommend
JGShining
 

  
  水题,简单数学题。
  题不难,想到了就很简单。一开始想了一大堆麻烦方法,后来看别人的解题报告,发现用对数就可以解决。果然学好数学相当重要 - -|||
 
Code:
  先用递归来做,发现会超时。
 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 //用递归来做,递归方程:
 6 //f(n) = (n==1) ? 0 : log10(n)+f(n-1)
 7 //but 数太大会超时
 8 
 9 double f(int n)
10 {
11     if(n==1)
12         return 0;
13     else
14         return log10(double(n))+f(n-1);
15 }
16 int main()
17 {
18     int t,n;
19     cin>>t;
20     while(t--){
21         cin>>n;
22         cout<<(int)f(n)+1<<endl;
23     }
24 }

  无奈换用循环,其实我是想练习一下递归的……

 1 #include <iostream>
 2 #include <cmath>
 3 using namespace std;
 4 
 5 //求阶乘值的位数可以用对数(log)来求
 6 //例:10!的位数
 7 //  log10(10*9*8*7*6*5*4*3*2*1) + 1
 8 //  = log10(10) + log10(9) + …… + log10(2) + log10(1) + 1
 9 //  = 7
10 //以下使用循环来做
11 
12 int main()
13 {
14     int t,n;
15     cin>>t;
16     while(t--){
17         cin>>n;
18         double sum=0;
19         for(int i=1;i<=n;i++)
20             sum+=log10(double(i));
21         cout<<int(sum)+1<<endl;
22     }
23     return 0;
24 }

Freecode : www.cnblogs.com/yym2013

原文地址:https://www.cnblogs.com/yym2013/p/3255093.html