Leftmost Digit |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 1602 Accepted Submission(s): 724 |
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 |
Author
Ignatius.L
|
数论题,着实想不明白,看了网上的思路,
n^n = a * 10^b;
将乘方转化为科学计数法,则此时floor(a)就是我们要就的Leftmost Digit.
两边同时取log10,
n * lg(n) = lg(a) + b;
考虑到科学计数法的表达,a < 10,则lg(a) < 1; 则 b 为 n * lg(n) 的整数部分,lg(a) 为小数部分;
则 lg(a) = n * lg(n) - b; b = floor(n * lg(n));
运用这个神奇的性质,我们可以求一个很大很大的数的前n位数字是什么
对于一个>=1的正整数m,10^(log10(m)-(int)log10(m))这个值,是原值m的1/k,k=1,10,100,1000...
为什么呢,看下面:
m=375,375=10^2.5740312677277188
对于一个>=1的正整数m,我们假设m=10^(a+b),a为指数的整数部分,b为指数的小数部分
(对比上面,如果m=375,那么a=2,b=0.5740312677277188)
则log10(m)-(int)log10(m)=(a+b)-a=b; 那么10^b是什么东西呢?
对于任意数m,m=10^(a+b)=10^a*10^b,显然10^a={1,10,100,1000,10000...};
则10^b就是Leftmost Digit
但是代码却很简单注意a=num*log10(num*1.0)-(__int64)(num*log10(num*1.0))
代码:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int cas;
cin>>cas;
int num;
while(cas--)
{
cin>>num;
double a=num*log10(num*1.0)-(__int64)(num*log10(num*1.0));
double b=pow(10.0,a);
cout<<int(b)<<endl;
}
return 0;
}