Files
rippled/include/xrpl/basics/MathUtilities.h
Bart 1d42c4f6de refactor: Remove unnecessary copyright notices already covered by LICENSE.md (#5929)
Per XLS-0095, we are taking steps to rename ripple(d) to xrpl(d).

This change specifically removes all copyright notices referencing Ripple, XRPLF, and certain affiliated contributors upon mutual agreement, so the notice in the LICENSE.md file applies throughout. Copyright notices referencing external contributions remain as-is. Duplicate verbiage is also removed.
2025-11-04 08:33:42 +00:00

50 lines
1.7 KiB
C++

#ifndef XRPL_BASICS_MATHUTILITIES_H_INCLUDED
#define XRPL_BASICS_MATHUTILITIES_H_INCLUDED
#include <algorithm>
#include <cassert>
#include <cstddef>
namespace ripple {
/** Calculate one number divided by another number in percentage.
* The result is rounded up to the next integer, and capped in the range [0,100]
* E.g. calculatePercent(1, 100) = 1 because 1/100 = 0.010000
* calculatePercent(1, 99) = 2 because 1/99 = 0.010101
* calculatePercent(0, 100) = 0
* calculatePercent(100, 100) = 100
* calculatePercent(200, 100) = 100 because the result is capped to 100
*
* @param count dividend
* @param total divisor
* @return the percentage, in [0, 100]
*
* @note total cannot be zero.
* */
constexpr std::size_t
calculatePercent(std::size_t count, std::size_t total)
{
assert(total != 0); // NOTE No XRPL_ASSERT here, because constexpr
return ((std::min(count, total) * 100) + total - 1) / total;
}
// unit tests
static_assert(calculatePercent(1, 2) == 50);
static_assert(calculatePercent(0, 100) == 0);
static_assert(calculatePercent(100, 100) == 100);
static_assert(calculatePercent(200, 100) == 100);
static_assert(calculatePercent(1, 100) == 1);
static_assert(calculatePercent(1, 99) == 2);
static_assert(calculatePercent(6, 14) == 43);
static_assert(calculatePercent(29, 33) == 88);
static_assert(calculatePercent(1, 64) == 2);
static_assert(calculatePercent(0, 100'000'000) == 0);
static_assert(calculatePercent(1, 100'000'000) == 1);
static_assert(calculatePercent(50'000'000, 100'000'000) == 50);
static_assert(calculatePercent(50'000'001, 100'000'000) == 51);
static_assert(calculatePercent(99'999'999, 100'000'000) == 100);
} // namespace ripple
#endif