经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C++ » 查看文章
(杭电 1097)A hard puzzle - cafu-chino
来源:cnblogs  作者:cafu-chino  时间:2018/12/7 9:33:35  对本文有异议

A hard puzzle

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

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

  1. 7 66
  2. 8 800

Sample Output

  1. 9
  2. 6

这道题给把我整的自闭了(′-ι_-`)

一开始根本不知道快速幂的算法,总是会TLE

(这是我之前写的暴力代码,直接起飞233333)

  1. #include <stdio.h>
  2. int main() {
  3. int a,b,t;
  4. while(scanf("%d%d",&a,&b) != EOF) {
  5. t=a;
  6. if(b > 1)
  7. for(int i=2; i <= b; i++) {
  8. t=t*a;
  9. t=t%10;
  10. }
  11. printf("%d\n",t);
  12. }
  13. return 0;
  14. }

后来Dalao给我讲了讲快速幂,在迷茫之中终于搞懂了(顺便来一句,快速幂真相);
(以下为快速幂的大体解释)

  1. int ksm(int a,int b)
  2. {
  3. int ans=1;
  4. while(b)
  5. {
  6. if(b & 1)
  7. ans=ans*a%10;
  8. a=a*a%10;
  9. b=b >> 1;
  10. }
  11. return ans;
  12. }
  13. /*
  14. 总体上来讲就是化成二进制后用二分法思想将一个大幂次分解为若干个小幂次:
  15. 'a^n=[(a)*(二进制最后一位)]*[(a^2)*(二进制倒数第二位)]*[(a^4)*(二进制倒数第三位)]*[(a^8)*(二进制倒数第四位)]*[(a^16)*(二进制倒数第四位)]*[(a^32)*······';
  16. */
  17. //程序运行以'a^13'为例:
  18. //'13'转化二进制'1101';
  19. **//位运算(等价于'a%2')取二进制最后一位;
  20. //为'1',把二分开的项运算出来放入结果,否则只进行二分
  21. //位移(比如第一步'1 1 0 1'位移就相当于去掉二进制最后一位)'1 1 0 1';
  22. // ^ ^
  23. //返回**步进行,直到'b == 0';
  24. //据二分法,得'a^13=[(a^1)*1]*[(a^2)*0]*[(a^4)*1]*[a(a^8)*1]';

由快速幂可以得出题解(因为ans计算时要考虑溢出问题所以改用long long变量储存)

样例答案(刚刚接触点c++,有点乱。。。)

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. long long ksm(long long a,long long b) //快速幂
  4. {
  5. long long ans=1;
  6. while(b)
  7. {
  8. if(b & 1)
  9. ans=ans*a%10;
  10. a=a*a%10;
  11. b=b >> 1;
  12. }
  13. return ans;
  14. }
  15. int main()
  16. {
  17. long long a,b;
  18. while(scanf("%lld%lld",&a,&b) != EOF)
  19. printf("%lld\n",ksm(a,b));
  20. return 0;
  21. }

(ps:日后我会填补快速乘的坑 ~ ヾ(=?ω?=)o)

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号