uva11029 - Leading and Trailing n^k保留前三位

Problem C

Leading and Trailing

Time limit: 2 seconds

 

Apart from the novice programmers, all others know that you can’t exactly represent numbers raised to some high power. For example, the C functionpow(125456, 455) can be represented in double data type format, but you won’t get all the digits of the result. However we can get at least some satisfaction if we could know few of the leading and trailing digits. This is the requirement of this problem.

 

Input

 

The first line of input will be an integer T<1001, where T represents the number of test cases. Each of the next T lines contains two positive integers,n and k. n will fit in 32 bit integer andk will be less than 10000001.

 

Output

 

For each line of input there will be one line of output. It will be of the format LLL…TTT, where LLL represents the first three digits ofn^k and TTT represents the last three digits of n^k. You are assured thatn^k will contain at least 6 digits.

 

 

Sample Input

Output for Sample Input

2

123456 1

123456 2

123...456

152...936


  这道题后三位快速幂取模就行了,但是前三位怎么做是个难点。

  n^k=10^(logn^k),设x是logn^k的整数部分,y是logn^k的小数部分,那么n^k=10^(x+y)=10^x * 10^y。由于10^x只改变小数点的位数,对数的值是不影响的。0<=y<1,所以1<=10^y<10,要保留3位,所以最后再乘以100就行了。

  这里有个新函数咯,fmod(a,b),就是a对b取模余下的包括小数部分,a,b都是浮点型,所以fmod(k*log10(n),1)就是y。

 

#include<cstring>
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
#define INF 0x3f3f3f3f
using namespace std;
long long bigpow(long long x,long long n,int M){
    long long ret=1,t=x%M;
    while(n){
        if(n&1) ret=ret*t%M;
        t=t*t%M;
        n>>=1;
    }
    return ret;
}
int main(){
    freopen("in.txt","r",stdin);
    int T;
    scanf("%d",&T);
    while(T--){
        int N,K,left,right;
        scanf("%d%d",&N,&K);
        left=100*pow(10,fmod(K*log10(N),1));
        right=bigpow(N,K,1000);
        printf("%d...%03d\n",left,right);
    }
    return 0;
}



你可能感兴趣的:(uva11029 - Leading and Trailing n^k保留前三位)