beefviper

better total(), 5th draft

Sep 5th, 2018
96
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* total */
  2. BigNum BigNum::_total(const BigNum& _augend, const BigNum& _addend) {
  3.     BigNum sum;
  4.     sum.integer.clear();
  5.     sum.fraction.clear();
  6.  
  7.     const int numbase = _augend.base;
  8.     int carry = 0;
  9.  
  10.     // copy extra part of longer fraction
  11.     auto fracOffset = std::abs((int)_augend.fraction.size() - (int)_addend.fraction.size());
  12.     auto fracExtra = (_augend.fraction.size() > _addend.fraction.size()) ?
  13.         _augend.fraction.rbegin() : _addend.fraction.rbegin();
  14.  
  15.     sum.fraction.resize(fracOffset);
  16.  
  17.     std::copy(fracExtra, fracExtra + fracOffset, sum.fraction.begin());
  18.  
  19.     // add overlapping fraction part
  20.     carry = _sumDigit(_augend.fraction, _addend.fraction, sum.fraction, fracOffset, carry, numbase);
  21.  
  22.     // add integer part
  23.     carry = _sumDigit(_augend.integer, _addend.integer, sum.integer, 0, carry, numbase);
  24.  
  25.     // add final carry, if needed
  26.     if (carry == 1) {
  27.         sum.integer.push_back(1);
  28.     }
  29.  
  30.     // and reverse vectors to proper order
  31.     std::reverse(sum.integer.begin(), sum.integer.end());
  32.     std::reverse(sum.fraction.begin(), sum.fraction.end());
  33.  
  34.     return sum;
  35. }
  36.  
  37. /* sumDigit */
  38. int BigNum::_sumDigit(const std::vector<int>& _numOne, const std::vector<int>& _numTwo,
  39.     std::vector<int>& _result, int _offset, int _carry, int _numbase) {
  40.  
  41.     auto augIt = _numOne.rbegin();
  42.     auto addIt = _numTwo.rbegin();
  43.  
  44.     if (_numOne.size() > _numTwo.size()) {
  45.         augIt += _offset;
  46.     }
  47.     else if (_numTwo.size() > _numOne.size()) {
  48.         addIt += _offset;
  49.     }
  50.  
  51.     int carry = _carry;
  52.     int tempSum = 0;
  53.  
  54.     while (augIt < _numOne.rend() && addIt < _numTwo.rend()) {
  55.         tempSum = *augIt + *addIt + carry;
  56.         carry = 0;
  57.  
  58.         if (tempSum > (_numbase - 1)) {
  59.             tempSum -= _numbase;
  60.             carry = 1;
  61.         }
  62.  
  63.         augIt++; addIt++;
  64.         _result.push_back(tempSum);
  65.     }
  66.  
  67.     return carry;
  68. }
RAW Paste Data