diff options
author | Olivier Gayot <og@satcom1.com> | 2017-09-08 20:06:38 +0200 |
---|---|---|
committer | Olivier Gayot <og@satcom1.com> | 2017-11-19 14:00:59 +0100 |
commit | 589f8e2558d008c63892f2345b233e28d889620b (patch) | |
tree | f93c0989aabfea7fe46f9c06308e61ea883bc0e1 /number.cpp | |
parent | 671f3f8ca44382386daf63c70140742e61200c2e (diff) |
Added the addition of two numbers
We're using the grade school addition method to compute the sum of two
numbers of size n.
Signed-off-by: Olivier Gayot <og@satcom1.com>
Diffstat (limited to 'number.cpp')
-rw-r--r-- | number.cpp | 41 |
1 files changed, 41 insertions, 0 deletions
@@ -1,5 +1,46 @@ #include "number.h" +/* Operations {{{ */ + +number +number::operator+(const number &n) const +{ + /* We make sure our object is greater than or equal to n. */ + if (*this < n) { + return n.operator+(*this); + } + + number result; + + auto it = _operands.cbegin(); + auto it_n = n._operands.cbegin(); + + bool carry = false; + + while (it != _operands.cend()) { + const auto n1 = *it; + const auto n2 = *it_n; + + result._operands.push_back(n1 + n2 + (carry ? 1 : 0)); + + if (carry && (n1 == UINT64_MAX)) { + carry = true; + } else { + carry = ((UINT64_MAX - n1 - (carry ? 1 : 0)) < n2); + } + + ++it; + ++it_n; + } + + if (carry) { + result._operands.push_back(1); + } + + return result; +} + +/* }}} */ /* Comparison operators {{{ */ bool |