public class Solution { /** * @param a: A 32bit integer * @param b: A 32bit integer * @param n: A 32bit integer * @return: An integer */ public int fastPower(int a, int b, int n) { // write your code here // base case if(n == 0){ return 1 % b; } if(n == 1){ return a % b; } long ret = 0; // (a * b) % p = (a % p * b % p) % p ret = fastPower(a, b, n/2); ret *= ret; ret %= b; if(n % 2 == 1){ ret *= a % b; } return (int) (ret % b); } }
Saturday, February 17, 2018
140. Fast Power
(a * b) % p = (a % p * b % p) % p
Subscribe to:
Post Comments (Atom)
4. Ugly Number
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
-
Given a list, rotate the list to the right by k places, where k is non-negative. Wrong solution 1: public ListNode rotateRight(ListNo...
-
if (head == null || head . next == null ) { return head; } ListNode lessDummy = new ListNode (...
-
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
No comments:
Post a Comment