algorithm-dev

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub today2098/algorithm-dev

:heavy_check_mark: 繰り返し二乗法
(algorithm/Math/Algebra/power.hpp)

概要

$n$ を $k$ 乗した値 $n^k$ を求める(ただし,$k$ は非負整数).

本実装では「繰り返し二乗法」を用いており,計算量は $\mathcal{O}(\log k)$ となる.

参考文献

  1. “冪乗”. Wikipedia. https://ja.wikipedia.org/wiki/冪乗.

Required by

Verified with

Code

#ifndef ALGORITHM_POWER_HPP
#define ALGORITHM_POWER_HPP 1

#include <cassert>

namespace algorithm {

// 繰り返し二乗法.O(logK).
template <typename Type>
constexpr Type pow(Type n, long long k) {
    assert(k >= 0);
    Type res = 1;
    while(k > 0) {
        if(k & 1LL) res *= n;
        n *= n;
        k >>= 1;
    }
    return res;
}

}  // namespace algorithm

#endif
#line 1 "algorithm/Math/Algebra/power.hpp"



#include <cassert>

namespace algorithm {

// 繰り返し二乗法.O(logK).
template <typename Type>
constexpr Type pow(Type n, long long k) {
    assert(k >= 0);
    Type res = 1;
    while(k > 0) {
        if(k & 1LL) res *= n;
        n *= n;
        k >>= 1;
    }
    return res;
}

}  // namespace algorithm
Back to top page