HDU 1060 Leftmost Digit(求N^N的第一位数字 log10的巧妙使用)

Leftmost Digit

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


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
 
题目意思:
要你求N^N的值的第一位数字是什么
比如3^3=27
结果就是2
正常写肯定是不行的,因为n太大了
所以要换一种方法
我的思想:
m=n^n;两边同取对数,得到,log10(m)=n*log10(n);
    再得到,m=10^(n*log10(n));
    然后,对于10的整数次幂,第一位是1,
    所以,第一位数取决于n*log10(n)的小数部分
贴一下大佬的分析对我的思想做个补充(都是一个意思)

1.令M = N^N 
2.两边取对数,log10M = Nlog10N,得到M = 10^(Nlog10N) 
3.令N^(N*log10N) = a(整数部分) + b(小数部分),所以M = 10^(a+b) = 10^a *10^b,由于10的整数次幂的最高位必定是1,所以M的最高位只需考虑10^b 
4.最后对10^b取整,输出取整的这个数就行了。(因为0<=b<1,所以1<=10^b<=10对其取整,那么的到的就是一个个位,也就是所求的数)。

 code:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
    /*
    m=n^n;两边同取对数,得到,log10(m)=n*log10(n);
    再得到,m=10^(n*log10(n));
    然后,对于10的整数次幂,第一位是1,
    所以,第一位数取决于n*log10(n)的小数部分
    */
    int t;
    double x,y;
    LL result;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        x=n*log10(n);
        y=(LL)x;
        x=x-y;
        result=(LL)pow(10.0,x);
        cout<<result<<endl;
    }
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/yinbiao/p/9327487.html