Leftmost Digit(数论)

来源:互联网 发布:大数据开发工程师待遇 编辑:程序博客网 时间:2024/05/16 11:29

杭电地址:http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=2§ionid=1&problemid=11

Leftmost Digit

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1759 Accepted Submission(s): 788 
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
234
 
Sample Output
22
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.

显然,第一眼看去就知道pow(n,n)不行,没这么大的数,double也不够大。假如给你一个大数,你会用什么方法求最高位呢?不断除10?显然不现实,直接引入结论:

给你一个数,比如a=3415774,求最高位,就那个3,该问题等于求b=3.415774的整数位,这个容易求。

那怎么把3415774变成3.415774呢?我们发现:

log(3415774)=log(1000000)+log(3.415774)=6+log(3.415774);后者小于1.

那么a=n^n的问题就变成了求log(n^n)的小数位的问题了。log(n^n)=n*log(n); 解决了n的n次过大的问题。所以。

---------------------------------

index=nlog(n);

pow(10,index-floor(index));

问题解决了(想想0^0的情况,刚好一致)

还要注意c的log是ln,要用请用log10(),要么log(x)/log(10)

#include <iostream>#include <cmath>using namespace std;int main(){int n;cin>>n;while(n--){   double d;   cin>>d;   double ind=d*log(d)/log(10.0);   cout<<(int)pow(10.0,ind-floor(ind))<<endl;}return 0;}

其中的知识点还有:floor()函数。ceil()函数

函数名: ceil
用 法: double ceil(double x);
功 能: 返回大于或者等于指定表达式的最小整数
头文件:math.h
函数名: floor
功 能: 返回小于或者等于指定表达式的最大整数
用 法: double floor(double x);
头文件:math.h
综合百度得:
ceil 是“天花板”floor 是 “地板”一个靠上取值,另一个靠下取值,如同天花板,地板。

问题扩展:

想想,只要改一下下,就可以求把结果转化成任意进制后的最高位的算法了~~