Leading and Trailing
LightOJ - 1282
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的前三位数和后三位数。
思路:
后三位数:快速幂对1000取模求nk。
前三位数(重点):设nk = x * 10m(科学计数法),则lg(nk) = lg(x * 10m) 即 k * lgn = lgx + m
lgx为k * lgn的小数部分,m为k * lgn的整数部分,则lgx=k * lgn-(int)k * lgn
a.bcdefgh = 10x,abc.defgh = 10x+2,则abc=(int)10x+2
ac代码:
#include <math.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <stack>
using namespace std;
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
typedef long long ll;
typedef pair<int, int> PII;
ll pmi(int a, int k, int p) {
ll res = 1;
while (k) {
if (k & 1) {
res = res * a % p;
}
k >>= 1;
a = a * a % p;
}
return res;
}
int main() {
int t;
scanf("%d", &t);
ll n, k;
for (int tt = 1; tt <= t; tt++) {
scanf("%lld%lld", &n, &k);
double x = k * log10(n) - (int)(k * log10(n));
int a = pow(10, x + 2);
int b = pmi(n % 1000, k, 1000);
printf("Case %d: %d %03d\n", tt, a, b);
}
return 0;
}