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

LintCode-Fast Power

时间:2014-12-25 06:35:20      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

Calculate the an % b where a, b and n are all 32bit integers.

Example

For 231 % 3 = 2

For 1001000 % 1000 = 0

Challenge

O(logn)

Solution:

 1 class Solution {
 2     /*
 3      * @param a, b, n: 32bit integers
 4      * @return: An integer
 5      */
 6     public int fastPower(int a, int b, int n) {
 7         if (n==0) return 1%b;
 8 
 9         int res = fastPowerRecur(a,b,n);
10         return res;
11     }
12 
13     public int fastPowerRecur(int a, int b, int n){
14         if (n==1)
15             return a%b;
16     
17         long temp = fastPowerRecur(a,b,n/2);
18         temp = temp*temp%b;
19         int res = (n%2==0) ? (int) temp: (int)(temp*a%b);
20         return res;
21     }
22 };

 

LintCode-Fast Power

标签:

原文地址:http://www.cnblogs.com/lishiblog/p/4183800.html

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