快速幂和同余模

 

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

我的最初做法:

class Solution {
public:
    double Power(double base, int exponent) {
        double res = 1; 
        if(exponent >= 0)
        {
            for(int i = 0; i < exponent; i++)
                res *= base;
            return res;
        }
        else 
        {
            exponent = -exponent;
            for(int i = 0; i < exponent; i++)
            res *= base;
            return 1/res;
        }
        
    }
};

设置bool变量

class Solution {
public:
    double Power(double base, int exponent) {
        double res = 1; 
        bool flag = true;
        if(exponent < 0)
        {
            exponent = -exponent;
            flag = false;
        }
         for(int i = 0; i < exponent; i++)
                res *= base; 
         if(flag) 
             return res;
         else
            return 1/res;
    }
};

 正确做法:快速幂

class Solution {
public:
    double Power(double base, int exponent) {
        int p = abs(exponent);
        double ans = 1;
        while(p != 0)
        {
            if( p&1)
                ans *= base;
            base *= base;
            p>>=1;
        }
        return (exponent > 0)?ans:1/ans;
    }
};

 同余模:

同余模定理:a*b%m = [(a%m)*(b%m)]%m

证明如下:

因此a^b%m有如下公式:

总结一下就是:(a^2)%m = [(a%m)^2]%m;

同余模的作用就是为了防止乘法后得到的数太大,不能取模,所以把取模分散开,先把数取模然后再相乘。

快速幂和同余模结合一下:

例如:计算a^b%1000的值?

private static int cifang3(int a, int b) {  
    int s = 1;  
    while (b > 0) {  
        if (b % 2 == 1) {  
            s = s % 1000;  
            a = a % 1000;  //(a%m)2%m = a2%m
            s = s * a;  
        }  
        a = a % 1000;  //没有进入if条件语句的的取模
        a = a * a;  
        b = b >> 1;  
    }  
    return s% 1000;  
}  

 

posted @ 2018-03-09 17:14  Lune-Qiu  阅读(210)  评论(0编辑  收藏  举报