Background
It is dark at night.
It is silence at night.
It is she in the dark.
It is she in the silence.
Then a light appeared. A huge gate came into our sights, called
The Gate to Freedom
Problem
There‘re some words on the gate: "This gate will lead you to freedom. First, you have to open it. I have a problem for you to solve, if you answer it correctly, the gate will open!"
"Tell me, young boy, what is the leftmost digit of N^N?"
Input
This problem contains multiple test cases.
Each test case contains an integer N (N<=1,000,000,000).
Output
For each test case, output the leftmost digit of N^N.
Sample Input
3
4
Sample Output
2
2
Contest: A Great Beloved and My Gate to Freedom
There is a cx, there is a love_cx.
题意:
给定一个数字n , 问n的n次方的首位是多少.
解题思路:
直接暴力算n的n次方明显是不行的,用C写肯定会爆long long ,想一边暴力计算一边取模的同学可以打表看看,数字小的时候不会有误差,但是,数字大的时候会有1的误差。
而用JAVA的大数来进行计算则会超时。
那么只能从数学方面入手了。
n^n = k;
写成科学计数法后 k = a * 10^b
即 n^n = a * 10^b
两边取对数后
lg(n^n) = lg(a * 10^b)
即 n*lg(n) = lg(a) + b
那么b为多少呢?
因为 10^(n*lg(n)) = n^n
可知 [n*lg(n)] ([n*lg(n)] = n*lg(n) 向下取整)即等于 n^n 的位数 即 b
因此 n^n 的数字部分为 10^(n*lg(n) - [n*lg(n)])
我们只需要取第一位即可
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <sstream>
#define PI acos(-1.0)
#define eps 1e-8
const int inf = (1<<30) - 10;
using namespace std;
int main(){
//freopen("input.txt","r",stdin);
double n;
while(cin>>n){
double ans = ((log10(n))*n);
ans -= floor(ans);
ans = floor(pow(10.0,ans) + eps);
printf("%.6f\n",ans);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u012844301/article/details/47168847