杭電HDOJ 1060 解題思路



Leftmost Digit

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


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.
 

Author
Ignatius.L


解題思路:

對於M^N的最左側數的基本方法就是取對數。

M^N=10*N*log10(M);

log10(M)分成兩部分:整數部分s(10^s=100……00最左側永遠是1)、小數部分t;

取小數部分t,t*N=a+b,整數部分a(10^a=100……00最左側永遠是1)、小數部分b;

取小數部分b,pow(10,b)取左側第一位。


代碼:

#include <stdio.h>
#include <math.h>

int main(int argc, const char * argv[])
{
    int n,a,l;
    double t;
    
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d",&a);
        t=log10(a);
        l=t/1;
        t-=l;
        t*=a;
        l=t/1;
        t-=l;
        t=pow(10,t);
        l=t/1;
        while(l>9) l/=10;
        printf("%d\n",l);
    }
    
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章