码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1097 A hard puzzle(快速幂)

时间:2018-12-29 23:20:03      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:obj   二次   一个   div   case   规律   std   详细   位运算   

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
 
一开始这道题,就想,乘法取模嘛,然后超时,然后想起还有一直东西叫快速幂的(觉得百度百科写的挺详细的,当时就是从那里学的)
 1 #include<cstdio>
 2 int mod(int a,int b){
 3     int ans=1;
 4     a=a%10;
 5     while(b>0){
 6         if(b&1) //如果b是基数,位运算 
 7             ans=(ans*a)%10;
 8         b>>=1;//b/2 
 9         a=(a*a)%10;
10     }
11     return ans;
12 }
13 int main(){
14     int a,b;
15     while(scanf("%d%d",&a,&b)==2)
16         printf("%d\n",mod(a,b));
17     return 0;
18 }

然后看别人的代码,发现还有一种,找规律

0,1,5,6的任意次循环,它的尾数都是它本身

2循环为:2,4,8,6

3循环为:3,9,7,1

4循环为:4,6

7循环为:7,9,3,1

8循环为:8,4,2,6

9循环为:9,1

当然你可以直接就用数组输出,你也可以把每一个数都当成有4次循环

 1 #include<stdio.h>
 2 int main()
 3 {    int a,b,c[4]; 
 4   while(scanf("%d%d",&a,&b)!=EOF)  
 5   {     
 6       a=a%10;
 7       c[0]=a;//一次
 8      c[1]=(c[0]*a)%10;//二次
 9      c[2]=(c[1]*a)%10;//三次
10      c[3]=(c[2]*a)%10;//四次    
11      if(b%4==1)        
12         printf("%d",c[0]);
13      if(b%4==2)    
14         printf("%d",c[1]);
15      if(b%4==3)         
16         printf("%d",c[2]);
17      if(b%4==0)         
18         printf("%d",c[3]);
19     printf("\n");
20   }    
21   return 0;
22 }

 

HDU 1097 A hard puzzle(快速幂)

标签:obj   二次   一个   div   case   规律   std   详细   位运算   

原文地址:https://www.cnblogs.com/cake-lover-77/p/10197890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!