LightOJ – 1282 求取数字前三位和后三位

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

前三位的取法可以看作[latex]x.yz\times 10^m=n^k[/latex]对两边取log10就得到[latex]\lg x.yz + m =k\lg n[/latex]其中m为[latex]n^k[/latex]的位数-1,也就是[latex]\begin{bmatrix} k\lg n \end{bmatrix}[/latex]

注意[latex]log[/latex]函数要用[latex]log10[/latex],否则会出错,前者为以[latex]e[/latex]为底数

#include<iostream>
#include<stdio.h>
#include<math.h> 
using namespace std;
typedef long long ll;
ll t;
ll ksm(ll n,ll m,ll p)
{
	ll ans=1;
	for(;m;m>>=1,n=(n%p*n%p)%p)
	{
		if(m&1) ans=(ans%p*n%p)%p;
	}
	return ans%p;
}
int main()
{
	scanf("%lld",&t);
	for(int i=1;i<=t;i++)
	{
		printf("Case %d: ",i);
		ll n=0,k=0;
		scanf("%lld%lld",&n,&k);
		double g=k*log10(1.0*n)-(int)(k*log10(1.0*n));
		double le=pow(10,g);
		int lea=100*le;
		int tra=ksm(n,k,1000);
		printf("%d %03d\n",lea,tra);
	}
} 

 

发表评论

邮箱地址不会被公开。 必填项已用*标注