HDU1097 快速幂取模运算

A hard puzzle 

Description

lcy gives a hard puzzle to feng5166,lwg,JGShining and Ignatius:  gave a and b,how to know the a^b.everybody objects to this BT problem,so lcy makes the problem easier than begin.
this puzzle describes that: gave a and b,how to know the a^b's the last digit number.But everybody is too lazy to slove this problem,so they remit to you who is wise.

Input

There are mutiple test cases. Each test cases consists of two numbers a and b(0<a,b<=2^30)
Output
For each test case, you should output the a^b's  last digit number.

HDU中的水题,倒是简单,第一次,直接每次计算后取余数,代码如下:很可惜数字太大(0<a,b<=2^30),超时超内存

#include<iostream>

using namespace std;
int main(){
	long int a,b;
	while(cin>>a>>b){
		long int ans,x=a;
		for(int i=1;i<b;i++){
			ans=x*a%10;
			a=ans%10;
		}
		cout<<ans<<endl;
	}
	return 0; 
}

然后想到余数应该是不断循环的,可以用一个cir[10]数组存储循环节;同时用一个数记录循环节长度;然后取余在循环节中找就好

#include<iostream>
using namespace std;
int main(){
	long int a,b,x;
	while(cin>>a>>b){
		int s=0,cir[10];x=a;
		cir[0]=a%10;
		for(int i=1;i<10;i++){
			cir[i]=x*a%10;
			a=cir[i]%10;
			s++;
			if(cir[i]==cir[0])break;
		}
		cout<<cir[b%s-1]<<endl;
	}
	return 0;
}

结果,偶然发现,b是循环节长度整数倍时候,,,,,囧大法了,改了一下,还有一直用a有点数过大了

#include<iostream>
using namespace std;
int main(){
	long int a,b,x;
	while(cin>>a>>b){
		int s=0,cir[20];
		x=a%10;cir[0]=x;
		for(int i=1;i<10;i++){
			cir[i]=x*cir[i-1]%10;
			s++;
			if(cir[i]==cir[0])break;
		}
		int m=(b%s==0?s:b%s)-1;
		cout<<cir[m]<<endl;
	}
	return 0;
}

-------------------------------------------------------------我是快乐的分界线---------------------------------------------------------------


自己都看不懂自己一年前在搞什么飞机,刚水了篇快速幂的博客,补下这篇

#include <iostream>
using namespace std;
//b=1000001101(二进制)
//a^b=a^0+a^2+a^3+a^9
//O(log2(b))
typedef long long ll;

int qpow(ll a,ll b) { //a^b
	int res=1;
	while(b>0) {
		if(b&1)res=res*a%10;
		a=a*a%10;
		b>>=1;
	}
	return res;
}
int main() {
	ll a,b;
	while(~scanf("%lld%lld",&a,&b)) {
		int ans=qpow(a,b);
		printf("%d\n",ans);
	}
	return 0;
}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值