Leading and Trailing(基础数论+快速幂)

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的前三位和后三位

思路:后三位很好求,裸快速幂,mod=1000就行了,注意要补上前导0

求前三位就比较麻烦,需要转换一下思路

任何数x都可以表示成x=10^a的形式(如果x刚好是10的幂次,a是一个整数,否则的话a是一个浮点数),而a又可以表示成为 x+y 的形式,分别代表整数和小数部分,那么x就代表它的位数-1,10 ^ y就代表它的数值部分(科学计数法了解一下),那么只需要把10^y求出来乘以100,取整数部分,就是这个数字的前三位了。

接下来回归本题,若n=10^a ,(a可以通过求对数函数直接求出) 那么n^k=10 ^ ak ,根据上面我们求出ak的小数部分y之后,pow(10,y+2)就是答案啦(+2相当于上面的乘以100)

参考博客:http://www.bubuko.com/infodetail-2224145.html

#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
ll q_pow(ll a,ll b, ll p)
{
	ll ans=1;
	while(b)
	{
		if(b&1)
			ans=ans*a%p;
		a=a*a%p;
		b>>=1;
	}
	return ans;
}
int main()
{
	int t,cas=1;
	cin>>t;
	while(t--)
	{
		ll n,k;
		cin>>n>>k; 
		double a=log10(n*1.0);
		a*=(double)k;
		a=fmod(a,1);   //这个函数返回a的小数部分
		ll x=pow(10.0,a+2.0);
		ll y=q_pow(n,k,1000);
		printf("Case %d: %lld %03lld\n",cas++,x,y); 
	 } 
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值