HDU 1097 快速冪取餘(C語言)
阿新 • • 發佈:2019-02-01
A hard puzzle
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 39772 Accepted Submission(s): 14319
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分析:這是本人做的第一個快速冪取餘的題目,第一遍提交超時了,後來參考網上的思路,再加上自己的思路融合一下。程式碼如下:
#include<stdio.h> int main() { int a,b; int c[10][5]={ {0},{1},{2,4,8,6},{3,9,7,1},{4,6},{5}, {6},{7,9,3,1},{8,4,2,6},{9,1} }; while(~scanf("%d%d",&a,&b)) { switch(a%10) { case 0: printf("0\n");break; case 1: printf("1\n");break; case 2: printf("%d\n",c[2][(b-1)%4]);break; case 3: printf("%d\n",c[3][(b-1)%4]);break; case 4: printf("%d\n",c[4][(b-1)%2]);break; case 5: printf("5\n");break; case 6: printf("6\n");break; case 7: printf("%d\n",c[7][(b-1)%4]);break; case 8: printf("%d\n",c[8][(b-1)%4]);break; case 9: printf("%d\n",c[9][(b-1)%2]);break; } } return 0; }
思路2:思路連結 http://blog.csdn.net/lsldd/article/details/5506933程式碼如下:
#include <stdio.h> int main() { int a,b,ans,k; while(scanf("%d%d",&a,&b)!=EOF) { ans=1; k=a%10; while(b>0) { if(b%2==1) ans=(ans*k)%10; b=b/2; k=(k*k)%10; } printf("%d\n",ans); } return 0; }