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;
}