A hard puzzle
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 32851 Accepted Submission(s): 11754
Problem 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.
Sample Input
7 66 8 800
Sample Output
9 6
Author
eddy
一开始常规方法,时间超时。之后~
我也不知道 啥原理 他妈的一下子就水过去了 靠!服了,只不过在求快速幂的时候加了个%=10而已 原理以后深究
#include<iostream> using namespace std; int quickmi(int a,int b) { int r=1,base=a; while(b) { if(b&1) { r*=base; r%=10; } base%=10;base*=base; b>>=1; } return r; } int main() { int a,b; while(cin>>a>>b) { cout<<quickmi(a,b)<<endl; } return 0; }
网上搜罗了一下 有个更好理解的方法:每个底数的数字的n次方都是四位循环数字 4*n+1幂的尾数是底数的1次幂的尾数,注意可能出现幂能整除4的情况;
#include<iostream> using namespace std; int main() { int a,b; while(cin>>a>>b) { a%=10; int ls=a*a*a*a;//防止b==0,先初始化ls b%=4; for(int i=0;i<b;i++)//如果b本身就是小于4的,此时的幂b乘以a的四次方(ls)后相当于不乘 { ls*=a; ls%=10; } cout<<ls%10<<endl; } return 0; }