Leading and Trailing LightOJ

来源:互联网 发布:黑猫警长细思极恐 知乎 编辑:程序博客网 时间:2024/06/05 19:20
  1. 题目如下

    You are given two integers: n and k, your task is to find the most significant three digits, and least significant three digits 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 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,求n^k的前三位数和最后三位数;
    最后三位数可以用快速幂取模得到,前三位数需要用到一下技巧:
    n^k=10^(a*k)=10^(x+y),其中x为a*k的整数部分,y为a*k的小数部分,所求答案的后三位即10^(y+2)
    题目链接
#include<cmath>#include<cstdio>using namespace std;typedef long long ll;ll mod_pow(ll n,ll k){    ll res=1;    while(k){        if(k&1) res=res*n%1000;        n=n*n%1000;        k>>=1;    }    return res;}int main(){    int t,kase=0;    ll n,k,leading,trailing;    double ak,y;    scanf("%d",&t);    while(t--){        scanf("%lld%lld",&n,&k);        trailing=mod_pow(n,k);        ak=(double)k*log10((double)n);        y=fmod(ak,1.0);        leading=pow(10.0,y+2.0);        printf ("Case %d: ",++kase);        printf ("%lld %03lld\n",leading,trailing);    }    return 0;}
原创粉丝点击