zoukankan      html  css  js  c++  java
  • 快速幂

    快速幂算法

    实现 pow(xn) ,即计算 x 的 n 次幂函数(即,xn)。

    class Solution {
    public:
        double quickMul(double x, long long N) {
            if (N == 0) {
                return 1.0;
            }
            double y = quickMul(x, N / 2);
            return N % 2 == 0 ? y * y : y * y * x;
        }
    
        double myPow(double x, int n) {
            long long N = n;
            return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);
        }
    };

    class Solution {
    public:
        double quickMul(double x, long long N) {
            double ans = 1.0;
            // 贡献的初始值为 x
            double x_contribute = x;
            // 在对 N 进行二进制拆分的同时计算答案
            while (N > 0) {
                if (N % 2 == 1) {
                    // 如果 N 二进制表示的最低位为 1,那么需要计入贡献
                    ans *= x_contribute;
                }
                // 将贡献不断地平方
                x_contribute *= x_contribute;
                // 舍弃 N 二进制表示的最低位,这样我们每次只要判断最低位即可
                N /= 2;
            }
            return ans;
        }
    
        double myPow(double x, int n) {
            long long N = n;
            return N >= 0 ? quickMul(x, N) : 1.0 / quickMul(x, -N);
        }
    };
  • 相关阅读:
    51Nod1528 加号分配
    51Nod1679 连通率
    51Nod1679 连通率
    51Nod1426 沙拉酱括号
    51Nod1426 沙拉酱括号
    51Nod1678 lky与gcd
    51Nod1556 计算
    c学习第2天
    Stopwatch秒表的使用
    数据从.txt文件中导入数据库
  • 原文地址:https://www.cnblogs.com/qianxunslimg/p/15646234.html
Copyright © 2011-2022 走看看