Leftmost Digit

Problem Description
Given a positive integer N, you should output the leftmost digit of N^N.
 
Input
The 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).
 
Output
For 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.
先将N^N对数化,取10为底,又N^N可表示为a*10^x,其中9>=a>=1,故x为N^N的位数-1,eg:100=1*10^2 故x为2
lg(N^N) = lg(a*10^x) ;

化简        N*lg(N)  = lg(a) + x;

继续化       N*lg(N) - x = lg(a)

            a = 10^(N*lg(N) - x);

问题转化成求x:

因为1<=a<=9,所以lg(a)<1;

故x=(int) N*lg(N) 向下取整

最后(int)a就是最后的结果

 

View Code
 1 #include<iostream> 
 2 #include<cmath> 
 3 #include<cstdio>
 4 using namespace std;
 5 int main() 
 6 { 
 7     int n; 
 8     __int64 m;
 9      cin>>n; 
10     while(n--) 
11     { 
12         scanf("%I64d",&m);
13         double t = m*log10(m*1.0); 
14         t -= (__int64)t; 
15         __int64 ans = pow((double)10, t); 
16         printf("%I64d\n",ans); 
17     } 
18     return 0; 
19 } 

 

 

 

posted on 2012-04-27 19:57  L_S_X  阅读(117)  评论(0编辑  收藏  举报

导航