zoukankan      html  css  js  c++  java
  • 快速幂

    快速幂

    快速幂

    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

  • 相关阅读:
    vue-cli element axios sass 安装
    Rem-- ui图与适配手机的px换算
    REM
    Canvas画半圆扇形统计图
    在vue中安装SASS
    在vue中引用.SCSS的公用文件
    Echart--折线图手柄触发事件
    vue 脚手架webpack打包后,解决能看到vue源码的问题
    js 函数 /变量/ 以及函数中形参的预解析的顺序
    【算法日记】4.递归和快速排序
  • 原文地址:https://www.cnblogs.com/yangwen0228/p/6220419.html
Copyright © 2011-2022 走看看