| 1 | //! @file arithmetic.cpp |
| 2 | //! @author ryftchen |
| 3 | //! @brief The definitions (arithmetic) in the numeric module. |
| 4 | //! @version 0.1.0 |
| 5 | //! @copyright Copyright (c) 2022-2025 ryftchen. All rights reserved. |
| 6 | |
| 7 | #include "arithmetic.hpp" |
| 8 | |
| 9 | namespace numeric::arithmetic |
| 10 | { |
| 11 | //! @brief Function version number. |
| 12 | //! @return version number (major.minor.patch) |
| 13 | const char* version() noexcept |
| 14 | { |
| 15 | static const char* const ver = "0.1.0" ; |
| 16 | return ver; |
| 17 | } |
| 18 | |
| 19 | std::int32_t Arithmetic::addition(const std::int32_t augend, const std::int32_t addend) |
| 20 | { |
| 21 | return bitAdd(a: augend, b: addend); |
| 22 | } |
| 23 | |
| 24 | std::int32_t Arithmetic::subtraction(const std::int32_t minuend, const std::int32_t subtrahend) |
| 25 | { |
| 26 | return bitAdd(a: minuend, b: bitAdd(a: ~subtrahend, b: 1)); |
| 27 | } |
| 28 | |
| 29 | std::int32_t Arithmetic::multiplication(const std::int32_t multiplier, const std::int32_t multiplicand) |
| 30 | { |
| 31 | std::int32_t product = 0; |
| 32 | for (std::int32_t i = ((sizeof(std::int32_t) * 8) - 1); i >= 0; --i) |
| 33 | { |
| 34 | product <<= 1; |
| 35 | if ((multiplicand & (1 << i)) >> i) |
| 36 | { |
| 37 | product = bitAdd(a: product, b: multiplier); |
| 38 | } |
| 39 | } |
| 40 | return product; |
| 41 | } |
| 42 | |
| 43 | std::int32_t Arithmetic::division(const std::int32_t dividend, const std::int32_t divisor) |
| 44 | { |
| 45 | if (divisor == 0) |
| 46 | { |
| 47 | return 0; |
| 48 | } |
| 49 | |
| 50 | const std::int32_t absDividend = bitAbs(a: dividend); |
| 51 | const std::int32_t absDivisor = bitAbs(a: divisor); |
| 52 | std::int32_t quotient = 0; |
| 53 | std::int32_t remainder = 0; |
| 54 | for (std::int32_t i = ((sizeof(std::int32_t) * 8) - 1); i >= 0; --i) |
| 55 | { |
| 56 | quotient <<= 1; |
| 57 | remainder <<= 1; |
| 58 | remainder |= (absDividend & (1 << i)) >> i; |
| 59 | if (remainder >= absDivisor) |
| 60 | { |
| 61 | remainder = bitSub(a: remainder, b: absDivisor); |
| 62 | quotient |= 1; |
| 63 | } |
| 64 | } |
| 65 | if ((dividend ^ divisor) < 0) |
| 66 | { |
| 67 | quotient = bitSub(a: 0, b: quotient); |
| 68 | } |
| 69 | return quotient; |
| 70 | } |
| 71 | |
| 72 | std::int32_t Arithmetic::bitAdd(const std::int32_t a, const std::int32_t b) |
| 73 | { |
| 74 | const std::int32_t sum = a ^ b; |
| 75 | const std::int32_t carry = (a & b) << 1; |
| 76 | return (sum & carry) ? bitAdd(a: sum, b: carry) : (sum ^ carry); |
| 77 | } |
| 78 | |
| 79 | std::int32_t Arithmetic::bitSub(const std::int32_t a, const std::int32_t b) |
| 80 | { |
| 81 | return bitAdd(a, b: bitAdd(a: ~b, b: 1)); |
| 82 | } |
| 83 | |
| 84 | std::int32_t Arithmetic::bitAbs(const std::int32_t a) |
| 85 | { |
| 86 | const std::int32_t mask = a >> (sizeof(std::int32_t) * 8 - 1); |
| 87 | return (a ^ mask) - mask; |
| 88 | } |
| 89 | } // namespace numeric::arithmetic |
| 90 | |