LOJ1282 Leading and Trailing(数论)
链接:http://www.lightoj.com/volume_showproblem.php?problem=1282
题目
Time Limit: 2000ms Memory Limit: 32768KB
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次方的前3位和后3位。
分析
直接求必然爆炸,估计longlonglonglong都不可能行= =
1.后三位直接快速幂取模
2.前三位推导如下
设
nk=A
,则有:
klgn=lgA
–>
nk=10klgx
这时,我们已经可以得出A=pow(10,klog10(n))
那么,怎么得到我们需要的前三位呢?
重点!:将
klgn
分解为整数部分和小数部分,即
klgn=z+d
(z为整数部分,d为小数部分)。为什么这样呢?因为
10n
中n的整数部分并不会影响前三位,他只会产生100…00。
所以就简化成了讨论
10d
,得公式
pow(10,d) –> pow(10,fmod(klog10(n),(int)klog10(n))
3.莫名WA了几发之后发现了原因,由于拆分掉了整数部分,所以有可能出现前三位为00*或者0**的情况,所以输出用%03d搞定。
源码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<utility>
#include<sstream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x7fffffff;
const int MAXN = 1000000;
const int MOD = 1000000007;
ll upper,lowwer;
ll n,k;
double upper_double;
int quick_mod(ll x, ll n, int mod){
ll ret = 1;
while(n){
if(n&1)
ret = (ret%mod*x%mod)%mod;
x = (x%mod*x%mod)%mod;
n /= 2;
}
return ret;
}
int main(){
/*#ifdef LOCAL
freopen("C:\\Users\\JuneLynn Bian\\Desktop\\in.txt","r",stdin);
freopen(" C:\\Users\\JuneLynn Bian\\Desktop\\out.txt","w",stdout);
#endif // LOCAL*/
int t;
cin >> t;
for (int i = 1; i <= t; i++){
cin >> n >> k;
lowwer = quick_mod(n,k,1000);
//upper_double = pow(10, fmod(k*log10(double(n)),1) );
//upper = upper_double*100;
upper = (int)pow(10 , 2+fmod(k*log10(n),(int)(k*log10(n))) );
printf("Case %d: %lld %03lld\n",i,upper,lowwer);
}
return 0;
}