题目如下
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;
}
本文介绍了一种算法,用于计算给定两个正整数n和k时,n^k的前三位数和最后三位数。该算法利用了快速幂取模获取最后三位,并通过将n^k表示为10的指数形式来巧妙地找到前三位。
222

被折叠的 条评论
为什么被折叠?



