02分治算法-02fast-power
来源:互联网 发布:程序员被骗28万 编辑:程序博客网 时间:2024/05/16 14:13
计算an % b,其中a,b和n都是32位的整数。
样例
例如 231 %3 = 2
例如 1001000 %1000 = 0
挑战
O(logn)
=======================================================================
注意到 a2 % b =((a%b)*(a%b)) % b
故猜想到 an % b = ((an/2%b)*(an/2%b)) % b
这样只需计算 an/2 % b,再将结果平方即可。这样也就实现了O(logn)
public int fastPower(int a, int b, int n) { if (n == 1) return a % b; if (n == 0) return 1 % b; long product = fastPower(a, b, n / 2); product = (product * product) % b; if (n % 2== 1) { //n为奇数的情况 product = (product * a) % b; } return (int) product; }
0 0
- 02分治算法-02fast-power
- LeetCode[50]分治算法求解power(double,int)问题
- [刷题]Fast Power
- lintcode: Fast Power
- #140 Fast Power
- *[Lintcode]Fast Power
- Fast Power 解题报告
- LintCode 150 : Fast Power
- Fast Power--lintcode
- 02分治算法-01二分查找
- 02分治算法-03wood-cut
- BZOJ 3897 Power 分治
- 递归----Fast Power Show result
- [LintCode] 快速幂 Fast Power
- Lintcode140 Fast Power solution 题解
- 快速幂(Fast Power)
- 分治算法
- 分治算法
- Android中allowBackup属性的含义和危险性实例讲解
- 揭秘信用卡账单、支付宝背后的黑色产业链
- Activity生命周期详解(为什么不能在onPause里执行耗时操作)
- HDU1176
- 语音处理学习感悟汇总
- 02分治算法-02fast-power
- 【Distribution】分布式系统的事务处理
- Jmeter压测(给逗逗总结的)
- 欢迎使用CSDN-markdown编辑器
- 【跨进程】跨进程通信---AIDL
- POJ - 3279 枚举 [kuangbin带你飞]专题一
- iOS开发网络篇之文件下载、大文件下载、断点下载
- 排序算法:堆排序
- ListView实现局部更新的方法