zoukankan      html  css  js  c++  java
  • 快速幂和同余模

    给定一个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;  
    }  
  • 相关阅读:
    12 KLT算法
    1- js vue.js
    复用代码
    计算两个日期相隔的天数(jodd)
    [转]ORA-00907: 缺失右括号
    [转]sql server 数据库日期格式化函数
    [Oralce]Oralce格式化日期
    myeclipse内存配置
    cookie 编码问题
    [转]Oracle 操作字符串的函数
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/8534967.html
Copyright © 2011-2022 走看看