UVA 11029 Leading and Trailing

来源:互联网 发布:bi开发工程师转行java 编辑:程序博客网 时间:2024/05/17 22:32

You are given two integers: n and k, your task is to find the most significant three digits, and least significant three digits of n^k.

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 < 2^31) and k (1 ≤ k ≤ 10^7).

Output
For each case, print the case number and the three leading digits (most significant) and three trailing digits (least significant). You can assume that the input is given such that nk contains at least six digits.

Sample Input
5
123456 1
123456 2
2 31
2 32
29 8751919

Sample Output
Case 1: 123 456
Case 2: 152 936
Case 3: 214 648
Case 4: 429 296
Case 5: 665 669

大致题意:就是让你求n^k这个数的前三位数和最后三位数

思路:最后三位数我们可以直接对1000取模,用快速幂来做即可。对于前三位数我们可以这样想,假设 10^(a+b)=n^k ,a是整数,b是小数,那么我们需要的就求出b,然后取10^b的前三位即可.
b=log(n^k)-(int)log(n^k)=k*log(n)-(int)(k*log(n))

代码如下

#include <stdio.h>#include <bits/stdc++.h>using namespace std;#define LL long long int kpow(LL x,LL n)   {      int res=1;      while(n>0)      {          if(n & 1)              res=(res*x)%1000;          x=(x*x)%1000;          n >>= 1;      }      return res;  }  int main(){     LL n;    int k;    int T;    cin>>T;    int num=1;    while(T--)    {        cin>>n>>k;        int f=k*log10(n);        double t=pow(10,k*log10(n)-f);        int s=t*100;        //cout<<"Case "<<num<<": "<<s<<' '<<kpow(n,k)<<endl;        printf("Case %d: %d %03d\n",num,s,kpow(n,k));        num++;    }    return 0;}
原创粉丝点击