LintCode 快速幂
来源:互联网 发布:我国银行员工待遇数据 编辑:程序博客网 时间:2024/06/01 16:21
LintCode 快速幂
计算
样例
例如
例如
Solution:
显然不能先计算
因此,需要利用取模运算的乘法法则:
(a * b) % p = (a % p * b % p) % p
则有
注意:
1. n = 0 和 n = 1的情况
2. n为奇数时
Talk is cheap, show me the code!
class Solution { /* * @param a, b, n: 32bit integers * @return: An integer */ public int fastPower(int a, int b, int n) { // write your code here if (n == 0) return 1 % b; else if (n == 1) return a % b; else if (n < 0) return -1; long product = fastPower(a, b, n/2); product = (product*product) % b; if (n % 2 == 1) product = (product * (a%b))%b; //equal: product = (product * a)%b; return (int)(product); }};
Reference:
Lintcode: Fast Power 解题报告 - Yu’s Garden - 博客园
0 0
- LintCode-快速幂
- Lintcode快速幂
- lintcode-快速幂-125
- LintCode 快速幂
- Lintcode 快速幂
- lintcode之快速幂
- lintcode ----快速幂
- LintCode 140-快速幂
- LintCode :快速幂
- lintcode(140)快速幂
- 快速幂-LintCode
- [LintCode]140.快速幂
- 快速幂—LintCode
- [LintCode] 快速幂 Fast Power
- LintCode-剑指Offer-(140)快速幂
- lintcode刷题——快速幂
- LintCode
- lintcode--
- Android Wear 开发入门
- POJ 1936 All in All
- 解决利用模板装linux网卡eth1问题
- 如何在ubuntu14.04中安装IE8
- 黑马程序员--C语言自学笔记---10字符串、指针
- LintCode 快速幂
- SQL语句大全
- scala学习总结之二
- chmod----改变一个或多个文件的存取模式(mode)
- 项目第四天
- 在android studio中导入开源库PullToRefresh
- MYSQL数据库管理之权限管理
- POJ2104 K-th Number 题解&代码
- UIApplication的小结