Fast constexpr integer power (ipow)

A good optimizing compiler will transform tail-recursive functions to run as fast as imperative code. - SO

see also

ipow

#include <cstdint>

constexpr int64_t ipow(int64_t base, int exp, int64_t result = 1) {
  return exp < 1 ? result : ipow(base*base, exp/2, (exp % 2) ? result*base : result);
}

double^int

template <int N>
double power(double x) {
    if constexpr (N == 0) return 1.0;
    else if constexpr (N == 1) return x;
    else return x * power<N - 1>(x);
}

double result = power<3>(x);  // computes x^3 at compile time
Written on June 26, 2021, Last update on November 14, 2024
c++ math power recurse optimize fastware Fibonacci