• 快速幂和同余模


    给定一个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;  
    }  
  • 相关阅读:
    selenium2截图ScreenShot的使用
    selenium2断言类Assert的使用
    selenium2中的TestNg注解和数据驱动的简介及使用
    bash函数定义/使用/传参…
    bash字符串操作
    bash数组操作-定义/初始化/赋值…
    bash实例-参数/函数/统计IP
    01.AutoMapper 之约定(Conventions)
    00.AutoMapper 之入门指南(Getting Started Guide)
    AutoMapper
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/8534967.html
Copyright © 2020-2023  润新知