LightOJ 1282 - Leading and Trailing (求n^k的前三位和后三位)

1282 - Leading and Trailing
  PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB

You are given two integers: n and k, your taskis to find the most significant three digits, and least significant threedigits of nk.

Input

Input starts with an integer T (≤ 1000),denoting the number of test cases.

Each case starts with a line containing two integers: n (2≤ n < 231) and k (1 ≤ k ≤ 107).

Output

For each case, print the case number and the three leadingdigits (most significant) and three trailing digits (least significant). Youcan assume that the input is given such that nk contains atleast six digits.

Sample Input

Output for Sample Input

5

123456 1

123456 2

2 31

2 32

29 8751919

Case 1: 123 456

Case 2: 152 936

Case 3: 214 648

Case 4: 429 296

Case 5: 665 669

 


思路:后三位很好求,快速幂取模就好了,同样前三位我们也可以模拟快速幂来写,用double存储答案,模拟一下快速幂,中间记得转换就好了,注意输出为3位,如果后三位是022,那么必须输出022,不能输出22




ac代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<set>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
#define MAXN 101000
#define LL long long
#define ll __int64
#define INF 0xfffffff
#define mem(x) memset(x,0,sizeof(x))
#define PI acos(-1)
#define eps 1e-8
using namespace std;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
ll powmod(ll a,ll b,ll MOD){ll ans=1;while(b){if(b%2)ans=ans*a%MOD;a=a*a%MOD;b/=2;}return ans;}
double dpow(double a,ll b){double ans=1.0;while(b){if(b%2)ans=ans*a;a=a*a;b/=2;}return ans;}
//head
double change(double x)
{
    while(x>=1000.0)
    {
        x/=10.0;
    }
    return x;
}
int main()
{
    int t,i;
    int cas=0;
    scanf("%d",&t);
    while(t--)
    {
        ll n,k;
        scanf("%I64d%I64d",&n,&k);
        int ans2=(int)powmod(n,k,1000);
        double ans1=1.0,a=n*1.0;
        while(k)
        {
            if(k%2)
            {
                ans1=ans1*a;
                ans1=change(ans1);
            }
            a=a*a;
            a=change(a);
            k/=2;
        }
        printf("Case %d: %d %03d\n",++cas,(int)ans1,ans2);
    }
    return 0;
}


你可能感兴趣的:(LightOJ 1282 - Leading and Trailing (求n^k的前三位和后三位))