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.
感想:一看到大数求幂就想到了快速幂,之前还想着用字符数组装大数,输出字符数组第一位再转换成数值,后来想想好像不太可行···然后没绷住搜了题解,思路是这样的:
需要用到科学记数法和对数运算的知识。
我们把numnum的值记作:
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)=nlog10(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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/关键在于公式,以及在于numlog10(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);
}
}
回到本题,这道题很好的运用了科学计数法的特点.
假设M=N^N,
则有M=,两边同时取对数log10(M)=log10(a)+n,其中1<=|a|<10,所以log10(a)必然表示的是log10(M)的小数部分,
(因为log10(10)=1,log10(1)=0所以1<=a<10的对数肯定小于1而大于等于0),所以,当务之急是将log10(M)的小数部分找到.
这个比较容易,我们只需要log10(M)-floor(log10(M)) 即可.//floor函数表示向下取整.
#include<stdio.h>
#include<math.h>
#include<limits.h>
int main()
{
int T;
double sum,logSum,DecSum ;
scanf("%d",&T) ;
while(T--)
{
scanf("%lf",&sum);
logSum = sum * log10(sum);
DecSum=pow(10.,logSum-(long long)logSum); //用floor或者(long long),不能用(int)
printf("%d\n",(int)DecSum);
}
return 0;
}
//1000000000
注意边界点:1和1000000000.
拓展:
log10()函数的用法
决窍一:求整数n的位数.1+(int)log10(n).(注意:其中n>0)
#include<stdio.h>
#include<math.h>
int main()
{
double T,n;
while(scanf("%lf",&n)!=EOF)
{
T=log10(n);
printf("%d\n",1+(int)T); //输出n的位数
}
return 0;
}
决窍二:科学计数法中截取整数部分或者小数部分.
科学计数法表示M=a*10^m,其中1<=a<10,m为整数.两边取对数log10(M)=log10(a)+m.log10(a)表示的是小数部分,
m表示的是整数部分.要恢复a的值只需要10^log10(a).