清明节假期,大家都出去玩了。我却苦逼的一个人在实验室里刷题目QAQ..
Leftmost Digit |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 3215 Accepted Submission(s): 1418 |
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 |
这题用是不是有点眼熟?没错,前不久我们刚刚做过一道Rightmost Digit 的题目。
但是这题让我们求得是最高位的数字,所以不会像之前那题一样有捷径了。
如果想暴力解此题肯定会被判超时的。
这个时候我们只要用log函数就好了。
以下是大致思路:
假设一个数为 num 根据题意,我们要求num^num 的最高位。
其实num^num 根据科学计数法,可以表示为a*10^n。
a的整数位即最高位的数。
所以有 num^num=a*10^n
两侧同时取对数:num*lg(num)=lg(a)+n
则有:lg(a)=num*lg(num)-n
即:a=10^(num*lg(num)-n)
其中,n等于int(num*lg(num)) //因为int(lg(num^num))就是它的十的幂数!
因此a=10^(num*lg(num)-int(num*lg(num)) //做题时请把int换成long long int 否则会溢出超时
——————————————————————————————————————————————————
在做题时,如果要强制转换类型,请以(int)(x) 的形式转换,否则系统会判为Compilation Error
#include<stdio.h>
#include<math.h>
int main()
{
double a,num,zon,b;
int zu;
scanf("%d",&zu);
while(zu--){
scanf("%lf",&num);
b=log10(num); //取对数
zon=num*b;
a=pow(10,(zon-(long long int)(zon)));
for(int i=0;a>=10;i++){
a/=10;
}
printf("%d\n",(long long int)(a));//必须用long long int 否则还是太大溢出
}
}