diff options
author | Hendiadyoin1 <leon2002.la@gmail.com> | 2022-01-27 13:22:23 +0100 |
---|---|---|
committer | Brian Gianforcaro <b.gianfo@gmail.com> | 2022-02-06 17:52:33 +0000 |
commit | 581c23dc55220f0a306a8284e525bd8ef55f7f00 (patch) | |
tree | 677f95f09e197cd4f60bfad7eb067faa2157209d /AK/IntegralMath.h | |
parent | 64f135d90f2d4fb9b3b13712cf2be1f3eb65d50d (diff) | |
download | serenity-581c23dc55220f0a306a8284e525bd8ef55f7f00.zip |
AK: Introduce IntegralMath.h starting with pow<I>
Diffstat (limited to 'AK/IntegralMath.h')
-rw-r--r-- | AK/IntegralMath.h | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/AK/IntegralMath.h b/AK/IntegralMath.h new file mode 100644 index 0000000000..03436832e1 --- /dev/null +++ b/AK/IntegralMath.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2022, Leon Albrecht <leon2002.la@gmail.com> + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include <AK/Concepts.h> +#include <AK/Types.h> + +#include <AK/Format.h> + +namespace AK { + +template<Integral I> +constexpr I pow(I base, I exponent) +{ + // https://en.wikipedia.org/wiki/Exponentiation_by_squaring + if (exponent < 0) + return 0; + if (exponent == 0) + return 1; + + I res = 1; + while (exponent > 0) { + if (exponent & 1) + res *= base; + base *= base; + exponent /= 2u; + } + return res; +} + +} |