numerics 0.1.0
Loading...
Searching...
No Matches
integer_pow.hpp
Go to the documentation of this file.
1/// @file integer_pow.hpp
2/// @brief Compile-time integer exponentiation via repeated squaring
3#pragma once
4
5namespace num {
6
7/// @brief Compute x^N at compile time via repeated squaring.
8template<int N, typename T>
9constexpr T ipow(T x) noexcept {
10 static_assert(N >= 0, "ipow: exponent must be non-negative");
11 if constexpr (N == 0)
12 return T(1);
13 if constexpr (N == 1)
14 return x;
15 if constexpr (N % 2 == 0) {
16 const T half = ipow<N / 2>(x);
17 return half * half;
18 } else {
19 return x * ipow<N - 1>(x);
20 }
21}
22
23} // namespace num
constexpr T ipow(T x) noexcept
Compute x^N at compile time via repeated squaring.