快速幂或找规律求a的b次方的最后一位-HDU1097

来源:互联网 发布:怎么查看数据库ip 编辑:程序博客网 时间:2024/05/16 16:22

https://vj.xtuacm.cf/contest/view.action?cid=125#problem/E

A hard puzzle
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

#include<cstdio>  int mod(int a,int b,int k){      int ans=1;      a=a%k;      while(b>0){          if(b%2==1) ans=(ans*a)%k;          b/=2;          a=(a*a)%k;      }      return ans;  }  int main(){      int a,b;      while(scanf("%d%d",&a,&b)==2)          printf("%d\n",mod(a,b,10));      return 0;  }  

这是直接的求法。看别人的题解,竟然还有一个规律:

尾数为0,1,5,6的不管是多少次方尾数依然不变,而尾数为4和9的每2次循环,

2,3,7,8为每4次循环。循环结果如下:

0,1,5,6:位数永远是0,1,5,6

2:6,2,4,8循环

3:1,3,9,7循环

4:6,4循环

7:1,7,9,3循环

8:6,8,4,2循环

9:1,9循环

好的,可以水过了:

#include<cstdio>  int div[10]={1,1,4,4,2,1,1,4,4,2};  int f[10][4]={{0},{1},{6,2,4,8},{1,3,9,7},{6,4},{5},{6},{1,7,9,3},{6,8,4,2},{1,9}};  int main(){      int a,b;      while(scanf("%d%d",&a,&b)==2)          printf("%d\n",f[a%10][b%div[a%10]]);      return 0;  } 
原创粉丝点击