Thursday, April 9, 2015

Fast Power

Fast Power

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)


------------------- thinking -----------------------------------------
result * base & base * base might overflow, so please use long long as the type of these two variables
-------------------- codes -------------------------------------------
class Solution {
public:
    /*
     * @param a, b, n: 32bit integers
     * @return: An integer
     */
    int fastPower(int a, int b, int n) {
        // write your code here
        if (n == 0) {
            return 1 % b;
        }
        if (n == 1) {
            return a % b;
        }
        long long base = a % b;
        long long result = 1;
        int bit_n = n;
        while (bit_n > 0) {
            if (bit_n % 2) {
                result = (result * base) % b;
            }
            bit_n = bit_n/2;
            base = (base * base) % b;
        }
        return result;
    }
};

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. The concept of calculating 'a % b' efficiently with O(logn) is fascinating, and it's a great example of algorithm optimization. It's like finding the hidden power in fast calculations.

    While we explore the intricacies of fast power, it's also essential to consider the real-world applications of such optimizations. In some cases, it might even be related to the compensation of professionals working with complex algorithms, like those discussed atH1b Salary Data. This site is a valuable resource for understanding the financial aspects of careers in the tech industry, where algorithmic expertise is highly valued.

    In the world of numbers and algorithms, it's always great to discover ways to make complex calculations more efficient. Keep up the good work, and let's continue to explore the fascinating world of algorithms and their applications in our careers.

    ReplyDelete