zoukankan      html  css  js  c++  java
  • lintcode140

    Calculate the a^n % b where a, b and n are all 32bit integers.
    Example
    For 231 % 3 = 2
    For 1001000 % 1000 = 0
    Challenge
    O(logn)
     
    这里想解决的问题是当n足够大的时候,a^n会很大,超出了表达范围. 通过取余法则(ab)%c = (a%c)(b%c)%c解决。
     
    细节:
    1.看到integer*integer的时候要小心可能会溢出,所以要用long来暂存。千万注意long的使用,如果你要解决溢出问题,你一定要在溢出可能发生之前就把数据结构换成long。int a; long result = a*a;没用的,右边还是按int运算法则来,该溢出已经变形了,把变形的赋值给long result,失败. 一定要long result = (long)a * a; 或者long result = a; result = result * result;
    2.还是小心别调用两次递归。这样就不是logn了。return mypow(x,n/2)*mypow(x,n/2)不是还是算了两次n/2规模的问题也就是n规模问题吗?正确的应该是mypow(x*x, n/2)或者temp = mypow(x,n/2); temp*temp。
     
    我的实现
    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
            
            if (n == 0) {
                return 1 % b;
            } else if (n == 1) {
                return a % b;
            } else if (n % 2 == 0) {
                long result = fastPower(a, b, n / 2);
                result = (result * result) % b;
                return (int) result;
            } else {
                long result = ((long)fastPower(a, b, n-1) * fastPower(a, b, 1)) % b;
                return (int) result;
            }
        }
    }

    网友优秀实现

    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
            
            if (n == 0) {
                return 1 % b;
            } else if (n == 1) {
                return a % b;
            } else if (n % 2 == 0) {
                long result = fastPower(a, b, n / 2);
                result = (result * result) % b;
                return (int) result;
            } else {
                long result = ((long)fastPower(a, b, n-1) * fastPower(a, b, 1)) % b;
                return (int) result;
            }
        }
    }
  • 相关阅读:
    第十一周课堂测试 -- 四则运算
    软件工程第十一周学习进度
    软件工程课堂测试2
    软件工程概论_课堂测试
    11.16 动手动脑
    动手动脑
    网络模型分析
    Actor模型原理
    linux下启动oracle
    Linux 环境下Oracle11g安装图文详细教程
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9446681.html
Copyright © 2011-2022 走看看