Fast Power--lintcode

Description

Calculate the an % b where a, b and n are all 32bit integers.

Example

For 2^31 % 3 = 2
For 100^1000 % 1000 = 0

看到这题我想到了我之前做过一题pow(x,n).是求x^n.我用了两种方法 。一种是递归,一种是二进制。网址: http://blog.csdn.net/liu981975231/article/details/77503785

这题首先我们用二进制:
解释你可以看我上面的网址,也可以看这一篇:幂模运算

public  int fastPower(int a, int b, int n) {
        // write your code here
        //利用 (a*c)%b=(c%b * a%b)%b;

        if(n==0) return 1;

        int result=1;
        while(n!=0){

            if( (n &1)!=0){
                //当b=2147483647时 result有可能超出范围
                result=(result%b * a%b)%b;
            }
            n>>=1;
            a*=a;
            System.out.println(result);
        }
        return result%b;
    }

说明:利用二进制这样写 会溢出。如 a b n分别为2 ,2147483647,2147483647。则在 result=(result%b * a%b)%b;这一步时,可能会溢出。因为当result相对较大时,而result%2147483647仍为result,然后再乘以a,就会溢出。这个溢出怎么解决呢????我想了很长时间,可惜能力有限没有想出来。所以我换成递归的方法。

public int fastPower(int a, int b, int n) {
        // write your code here       
        if (n == 1) {
            return a % b;
        } else if (n == 0) {
            return 1 % b;
        } else if (n < 0) {
            return -1;
        }

        // (a * b) % p = ((a % p) * (b % p)) % p
        // use long to prevent overflow
        long product = fastPower(a, b, n / 2);
        product = (product * product) % b;
        //
        if (n % 2 == 1) {
            product = (product * a) % b;
        }

        // cast long to int
        return (int) product;
    }

递归中,需要注意的是要分 n 是奇数还是偶数,奇数的话需要多乘一个 a, 保存乘积值时需要使用long型防止溢出,最后返回时强制转换回int

使用了临时变量product,空间复杂度为 O(1)O(1), 递归层数约为 \log nlogn, 时间复杂度为 O(\log n)O(logn), 栈空间复杂度也为 O(\log n)O(logn).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值