题意:给你一个m,求m!的位数。
数学证明:
假设m! = a * 10 ^ b ,求m! 的位数(10>a>=1,b∈R)。
对公式两边取log10();
得到: log10(a * 10 ^ b) = log10(m!);
化解公式:log10(a) + log10(10 ^ b) = log10(1 * 2 *3 * ....... * m);
-------->> log10(a) + b = log10(1)+ log10( 2) + log10(3) + . . . . . . + log10(m);
所以m!的位数为: b + 1 = log10(1)+ log10( 2) + log10(3) + . . . . . . + log10(m) - log10(a) + 1。
因此可以近似的写成 b + 1 <= log10(1)+ log10( 2) + log10(3) + . . . . . . + log10(m) + 1
(去掉 log10(a) < 1,毕竟a不好求,且10>a>=1 )。
测试例子:
1! = 1 = 1.0 * 10 ^ 0------------------------------------------------------------------- 1位 ->log10(1) = 0.0
2! = 2 = 2.0 * 10 ^ 0------------------------------------------------------------------- 1位 ->log10(2) = 0.3010299956639812
3! = 6 = 6.0 * 10 ^ 0------------------------------------------------------------------- 1位 ->log10(3) = 0.47712125471966244
4! = 24 = 2.4 * 10 ^ 1----------------------------------------------------------------- 2位 ->log10(4) = 0.6020599913279624
5! = 120 = 1.2 * 10 ^ 2--------------------------------------------------------------- 3位 ->log10(5) = 0.6989700043360189
6! = 720 = 7.2 * 10 ^ 2---------------------------------------------------------------- 3位 ->log10(6) = 0.7781512503836436
7! = 5040 = 5.04 * 10 ^ 3------------------------------------------------------------ 4位 ->log10(7) = 0.8450980400142568
8! = 40320 = 4.032 * 10 ^ 4--------------------------------------------------------- 5位 ->log10(8) = 0.9030899869919435
9! = 362880 = 3.6288 * 10 ^ 5;--------------------------------------------------- 6位 ->log10(9) = 0.9542425094393249
10!= 3628800 = 3.6288 * 10 ^ 6;---------------------------------------------- 7位 ->log10(10) = 1.0
log10(3.6288 * 10 ^ 6) = log10(3.6288) + log10(10*6) = 0.5597630328767937 + 6;
所以 位数( m! ) = b + 1;
Java AC 代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = 0, answer;
while (n-- > 0) {
m = sc.nextInt();
double sum = 0.0;
for (int i = 1; i <= m; i++) {
sum += Math.log10(i * 1.0);
}
answer = (int) sum + 1;
System.out.println(answer);
}
}
}
Big Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 31092 Accepted Submission(s): 14427
2 10 20
7 19