http://lightoj.com/volume_showproblem.php?problem=1282
Leading and Trailing
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu
Submit Status Practice LightOJ 1282
Description
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转化成a.bc * 10^m,这样abc就是前三位了,n^k = a.bc * 10^m
即lg(n^k) = lg(a.bc * 10^m)
<==>k * lg(n) = lg(a.bc) + lg(10^m) = lg(a.bc) + m
m为k * lg(n)的整数部分,lg(a.bc)为k * lg(n)的小数部分
x = lg(a.bc) = k * lg(n) - m = k * lg(n) - (int)(k * lg(n))
a.bc = pow(10, x);
abc = a.bc * 100;
这样前三位数abc便可以求出
#include<stdio.h> #include<math.h> #include<string.h> #include<stdlib.h> #include<algorithm> using namespace std; typedef long long ll; int Pow(int a, int b) { int ans = 1; a %= 1000; while(b) { if(b % 2 != 0) ans = (ans * a) % 1000; a = (a * a) % 1000; b /= 2; } return ans; }//快数幂 int main() { int t, n, k, p = 0; scanf("%d", &t); while(t--) { p++; scanf("%d%d", &n, &k); double m = k * log10(n) - (int)(k * log10(n)); m = pow(10, m); int x = m * 100; int y = Pow(n, k); printf("Case %d: %d %03d\n", p, x, y); } return 0; }