codex
Loading...
Searching...
No Matches
power.hpp
Go to the documentation of this file.
1#ifndef CODEX_MATH_POWER_H
2#define CODEX_MATH_POWER_H
3
4#include <cassert>
5#include <cmath>
6#include <concepts>
7
8namespace detail {
9
10template<typename T>
11constexpr T power(T b, T e) {
12 return e == T{} ? T{1} : b * power(b, e - T{1});
13}
14
15}
16
17template<typename T>
18concept arithmetic = requires (T t0, T t1) {
19 t0 + t1; t0 - t1; t0 * t1; t0 / t1; t0 % t1;
20 t0 += t1; t0 -= t1; t0 *= t1; t0 /= t1; t0 %= t1;
21};
22
23template<typename T>
24requires
25 std::semiregular<T>
26 && std::constructible_from<T, int>
27 && std::three_way_comparable<T>
29T power(T b, T e) {
30 assert(e >= T{0});
31 constexpr auto pow = detail::power<T>;
32 [[maybe_unused]] const T ib = b, ie = e;
33 T ret = T{1}; // x ^ y == 1 * x ^ y
34 for(; e != T{}; e /= T{2}) {
35 assert(ret * pow(b, e) == pow(ib, ie));
36 if(e % T{2} == T{1}) {
37 // x ^ (y + 1) == x * x ^ y
38 assert(pow(b, e) == b * pow(b, e - T{1}));
39 ret *= b;
40 }
41 // x ^ y == (x * x) ^ (y / 2)
42 assert(pow(b, e - (e % T{2})) == pow(b * b, e / T{2}));
43 b *= b;
44 }
45 assert(ret * pow(b, e) == pow(ib, ie)); // r * x ^ 0 == r
46 assert(ret == pow(ib, ie));
47 return ret;
48}
49
50#endif
static const struct board b
Definition chess0.c:57
Definition power.hpp:18
Definition power.hpp:8
constexpr T power(T b, T e)
Definition power.hpp:11
T power(T b, T e)
Definition power.hpp:29
codex::refl::field_tuple_t< E > T
Definition soa.cpp:9
Definition mult_inh.c:26