1282 - Leading and Trailing 求n^k的前三位和後三位。
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
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.
分析:後三位直接快速冪取余得,對於體格給定的整數n可以寫成n = 10^a形式,其中a是浮點數, n ^ k = (10 ^ a) ^ k = (10 ^ x) * (10 ^ y), 其中x,y分別為ak的整數部分和小數部分,對於t=n^k這個數,他的位數由10^x決定,他的位數上的值由10^y決定。因此我們要求t的前三位,只用求出10^y就可以了。
double fmod (double x);
設返回值為 ret,那麽 x = n * y + ret,其中 n 是整數,ret 和 x 有相同的符號,而且 ret 的絕對值小於 y 的絕對值。如果 x = 0,那麽 ret = NaN。
fmod 函數計算 x 除以 y 的 f 浮點余數,這樣 x = i*y + f,其中 i 是整數,f 和 x 有相同的符號,而且 f 的絕對值小於 y 的絕對值。 代碼:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
const int maxn = 1e7+5;
const int mod = 1000;
int quickmi(int a, int b)
{
if(b == 0)
return 1;
int tmp = quickmi(a, b>>1);
tmp = tmp * tmp % mod;
if(b & 1)
tmp = tmp * (a % mod) % mod;
return tmp % mod;
}
int main(void)
{
int T, cas;
int n, m;
scanf("%d", &T);
cas = 0;
while(T--)
{
cas++;
scanf("%d%d", &n, &m);
int last = quickmi(n % 1000, m);
double y = 2.0 + fmod(m * log10(n * 1.0), 1);
int first = pow(10.0, y);
printf("Case %d: %03d %03d\n", cas, first, last);
}
return 0;
}
1282 - Leading and Trailing 求n^k的前三位和後三位。