HDU 1060 Leftmost Digit (数论,快速幂)
Given a positive integer N, you should output the leftmost digit of N^N.
InputThe input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
OutputFor each test case, you should output the leftmost digit of N^N.
Sample Input
2 3 4
Sample Output
2 2
Hint
In the first case, 3 * 3 * 3 = 27, so the leftmost digit is 2. In the second case, 4 * 4 * 4 * 4 = 256, so the leftmost digit is 2.
感想:一看到大数求幂就想到了快速幂,之前还想着用字符数组装大数,输出字符数组第一位再转换成数值,后来想想好像不太可行···然后没绷住搜了题解,思路是这样的:
需要用到科学记数法和对数运算的知识。
我们把num*num的值记作:num * num=a * 10^n,其中1<a<10;
那么,通过两边取对数的方法得到num * log10(1.0 * num)=log10(a)+n,这时0<log10(a)<1;
令x=n+log10(a),得到log10(a)=x-n;所以a=10^(x-n);
n为整数部分,log10(a)为小数部分,由x=n+log10(a),可知(int)x=n;
最终a=10^(x-n)=10^(x-(int)x)!
m=n^n(_int64);两边同取对数,得到,log10(m)=n*log10(n);再得到,m=10^(n*log10(n));
然后,对于10的整数次幂,第一位是1,所以,第一位数取决于n*log10(n)的小数部分。
1.求a=n^n的对数取整即位数m;【m=n*log10(n)
2.a除以10的m次方取整即最高位;【pow(n,n)/pow(10,m)
/*关键在于公式,以及在于num*log10(num)得到的结果要用long long转换为整数,而不能用int,因为int已经存不下了。*/ #include "stdio.h" #include "string.h" #include "math.h" int main(int n) { int C; double num; double a; double x; scanf("%d", &C); while(C--) { scanf("%lf", &num); x = num * log10(num); a = pow(10, x - (long long)x); printf("%d\n", (int)a); } }