Leftmost Digit(数论)

杭电地址: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
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.

显然,第一眼看去就知道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 是 “地板”
一个靠上取值,另一个靠下取值,如同天花板,地板。

问题扩展:

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值