• 快速幂


    快速幂

    快速幂

    1 题目

    计算an % b,其中a,b和n都是32位的整数。

    2 方法

    (ab)%c = (a%c * b%c)%c

    3 挑战

    O(log(n))

    4 思路

    采用二分法,每个幂次分为两半。

    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;
            }
    
            return (fastPower(a, b, n / 2) * fastPower(a, b, (n + 1) / 2)) % b;
        }
    };
    

    很容易就想到了,但是,运行时间不是log(n)的。因为,本来每计算一次都会减为原来的一半,但是,我们这里,每次运行了两次,那最终就是n次了。 所以,需要把每次的结果记录下来,就不需要运行两次了。这样,如果是奇数的话,还需要用之前的偶数次再乘以一次。

    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;
            }
    
            long product = fastPower(a, b, n / 2);
            product = product * product % b;
    
            if (n % 2 == 1) {
                product = (product * (a % b)) % b;
            }
    
            return (int)product;
        }
    };
    

    Date: 2016-12-25 14:15

    Created: 2016-12-31 周六 10:22

    Validate

  • 相关阅读:
    CSP-S全国模拟赛第三场 【nan死了】
    ●SCOI2018 AFO
    ●洛谷P2934 [USACO09JAN]安全出行Safe Travel
    ●洛谷P3233 [HNOI2014]世界树
    ●洛谷P2495 [SDOI2011]消耗战
    ●UOJ58 [WC2013]糖果公园
    ●洛谷P1903 [国家集训队]数颜色
    ●BZOJ 4237 稻草人
    ●Joyoi Normal
    ●CodeForces 698C LRU
  • 原文地址:https://www.cnblogs.com/yangwen0228/p/6220419.html
Copyright © 2020-2023  润新知