Leading and Trailing__LightOJ 1282(求n^k的前三位和后三位)

轻触打开原网站  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 n^k.

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 < 2^31) and k (1 ≤ k ≤ 10^7).

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 n^k 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


题目做法:
这算是一道简单的数论题吧,其实也不简单 ,磨了好久,可能是因为我太菜了吧~ _ ~ 
自己先暴力了一下试试,果然如我所料,直接溢出了,然后就在那磨啊磨啊,还是没搞通,就问了一下身边的巨佬,巨佬就是巨佬 ,tql, Orz膜拜

后三位好求,直接快速幂mod1000就Ojbk了,主要是前三位,    这时就需要一个很广的数学功底了
其实每个数都可以被表示成10 的多少次方并且
lg(数)=这个数的位数-1(真神奇,我也不明白,问的巨佬,举几个例子试试!!!)
然后换成10的一点几次方,就可以求得这个数的xx.xxxxx形式,然后扩大一下就OK了
还有就是要明白头文件<cmath>中的一些数学函数,比如 log、pow(浮点型数的次方)、modf(取某个浮点数的小数部分)还有个fmod    咱也不知道是个啥,以前根本没见过 ,但我用笨方法解决了^_^
搜了一下这个函数  这有个博客 可以了解一下[fmod和modf函数]数学库中的 fmod和modf函数  但我觉得还是我的笨方法好用呢,嘻嘻,好理解

还有就是要注意一下最后的输出格式 ,他们还讨论怎么输出 0  我直接来个 .3lld  简单明快
看代码吧:

#include<iostream>
#include<cstdio> 
#include<cmath>
using namespace std;
#define ll long long
 
ll quick_power(ll x,ll y){ //快速幂 
	ll res=1;
	while(y){
		if(y&1)res=res*x;
		x=x*x;
		y/=2;
	}
	return res;
}
ll quick_mod(ll x,ll y,ll mod){//快速mod 
	ll res=1;
	while(y){
		if(y&1)res=res*x%mod;
		x=x*x%mod;
		y/=2;
	}
	return res%mod;
}

int main()
{
	ll t,n,k;
	scanf("%lld",&t);
	for(ll i=1;i<=t;i++){
		scanf("%lld%lld",&n,&k);
		ll tail=quick_mod(n,k,1000);
//		int len=0;
//		ll power=quick_power(n,k);
//		while(power){
//			len++;
//			power/=10;
//		}
//		//printf("**%lld**\n",len); 
//		ll temp=quick_power(10,len-3);  
//		ll head=quick_power(n,k)/temp;  果然溢出了~_~  
		
		//lg(数)=这个数的位数-1 举几个例子试试!!! 
		ll len=k*log10(n*1.0);//位数减 1  
        double x=pow(10.0,k*1.0*log10(n*1.0)-len+1);//pow()==double型 的~~次幂 
        // x===2位整数+6位小数 前面的8个数位 
        while(x<100) x*=10;//扩充为 前面的3位数 
        ll head=x;//
        
		printf("Case %lld: %lld %.3lld\n",i,head,tail);
	//	if(i!=t)printf("\n");
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值