mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +00:00
AK: Introduce IntegralMath.h starting with pow<I>
This commit is contained in:
parent
64f135d90f
commit
581c23dc55
Notes:
sideshowbarker
2024-07-17 19:42:34 +09:00
Author: https://github.com/Hendiadyoin1 Commit: https://github.com/SerenityOS/serenity/commit/581c23dc552 Pull-request: https://github.com/SerenityOS/serenity/pull/12163 Reviewed-by: https://github.com/BertalanD ✅
3 changed files with 56 additions and 0 deletions
35
AK/IntegralMath.h
Normal file
35
AK/IntegralMath.h
Normal file
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
|
@ -33,6 +33,7 @@ set(AK_TEST_SOURCES
|
|||
TestHex.cpp
|
||||
TestIPv4Address.cpp
|
||||
TestIndexSequence.cpp
|
||||
TestIntegerMath.cpp
|
||||
TestIntrusiveList.cpp
|
||||
TestIntrusiveRedBlackTree.cpp
|
||||
TestJSON.cpp
|
||||
|
|
20
Tests/AK/TestIntegerMath.cpp
Normal file
20
Tests/AK/TestIntegerMath.cpp
Normal file
|
@ -0,0 +1,20 @@
|
|||
/*
|
||||
* Copyright (c) 2022, the SerenityOS developers.
|
||||
*
|
||||
* SPDX-License-Identifier: BSD-2-Clause
|
||||
*/
|
||||
|
||||
#include <LibTest/TestCase.h>
|
||||
|
||||
#include <AK/IntegralMath.h>
|
||||
|
||||
TEST_CASE(pow)
|
||||
{
|
||||
EXPECT_EQ(AK::pow<u64>(10, 0), 1ull);
|
||||
EXPECT_EQ(AK::pow<u64>(10, 1), 10ull);
|
||||
EXPECT_EQ(AK::pow<u64>(10, 2), 100ull);
|
||||
EXPECT_EQ(AK::pow<u64>(10, 3), 1'000ull);
|
||||
EXPECT_EQ(AK::pow<u64>(10, 4), 10'000ull);
|
||||
EXPECT_EQ(AK::pow<u64>(10, 5), 100'000ull);
|
||||
EXPECT_EQ(AK::pow<u64>(10, 6), 1'000'000ull);
|
||||
}
|
Loading…
Reference in a new issue