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的前三位和后三位
思路:后三位快速幂就行了,关键是这个前三位。
设x = log10 (n^k) = k * log10(n),那么10^x = n^k
.将x = a(整数) + b(小数),a决定了10^k的位数,b决定了10^k的具体数字。
double p=k*log10(n);
p=fmod(p,1); (fmod是浮点数取模)
int ans=(int)(pow(10,p)*100);
任意数可以转化成 X = 10^( x + y ) (x为整数,y为小数) 其中 10^x 来控制的是原数字,而具体这个数字等于多少,全靠10^y ,
那么 我们就可知道 10^y 就是我们要求的前n个数字还不会炸 long long (用double的话末尾消去,很适合)
这样我们就能保证前7位可知, 如果要前三位 只需要 10^(y) * 100 就好了。
fmod 是一个特殊函数 fmod(a,b) (a , b 为 浮点型) 得出的结果是 a / b 得出的结果的小数。。
前三位: 设x = log (n^k) = k * log10(n), 那么10^x = n^k.将x = a(整数) + b(小数), 整数部分10^a是小数点的位置,
并不影响前三位数字。 故只需要求出10^b取前三位。 使用fmod(a, 1)表示求浮点型数 a 的小数部分。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<iostream>
typedef long long ll;
using namespace std;
ll qsm(ll x,ll n,ll mod)///快速幂
{
ll res=1;
if(!n)return 1;
res=qsm(x*x%mod,n/2,mod);
if(n&1)res=res*x%mod;
return res;
}
int main()
{
int t,flag=1;
ll n,k;
scanf("%d",&t);
while(t--)
{
scanf("%lld %lld",&n,&k);
printf("Case %d: ",flag++);
int ans1,ans2;
ans1=(int)pow(10.0,2.0+fmod(k*log10(n*1.0),1.0));///前三
ans2=(int)qsm(n,k,1000);///后三
printf("%d %03d\n",ans1,ans2);
}
return 0;
}
头等舱可以优先登机,
银行VIP可以不用排队,
演唱会最贵的票位置也最好,
世界从不平等,
你有多努力就有多特殊。
女孩不一定要做大家庭的女强人,顶梁柱,但一定要做爸爸妈妈的顶梁柱!
因为他们老了,能靠的,只有你。