HDU 1097 A hard puzzle(简单快速幂)

<span style="font-size:18px;">http://acm.hdu.edu.cn/showproblem.php?pid=1097</span>

A hard puzzle

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34742    Accepted Submission(s): 12477


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
 

题意:求a的b次方所得结果的最后一位数。


解题思路:这是一题较简单的快速幂。以下是我对快速幂的理解,具体看代码。

 快速幂思路:
• 求a^b,是不是要把a乘b次呢?这样也行, 只是慢了点 • 例如求a^8,先把a乘a一次,得到a^2,然后把 a^2和a^2乘一次,得到a^4,然后把a^4和a^4乘一 下就得到a^8了 • 假如要求a^10呢?10=8+2,a^10=a^8*a^2 • 把10化为二进制, 10=1010(2),1010(2)=1000(2)+10(2)


<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:24px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int q_pow(int a,int b)
{
    int ans=1;//ans初始化为1
    while(b>0)
    {
        if(b&1) ans =(ans*a)%10;//如果b为奇数,把ans乘于a
        a =(a*a)%10;//把a变成a^a,并且%10,防止溢出
        b>>=1;//b右移一位,相当于除于2
    }
    return ans;
}
int main()
{
   int a,b;
   while(cin>>a>>b)
   {
       printf("%d\n",q_pow(a%10,b));//a%10在这是为了提速,原因自己想想
   }
   return 0;
}
</span></span></span>






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值