Multiplication.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * Copyright (c) 2020-2021, Dex♪ <dexes.ttp@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "UnsignedBigIntegerAlgorithms.h"
  8. namespace Crypto {
  9. /**
  10. * Complexity: O(N^2) where N is the number of words in the larger number
  11. * Multiplication method:
  12. * An integer is equal to the sum of the powers of two
  13. * according to the indices of its 'on' bits.
  14. * So to multiple x*y, we go over each '1' bit in x (say the i'th bit),
  15. * and add y<<i to the result.
  16. */
  17. FLATTEN void UnsignedBigIntegerAlgorithms::multiply_without_allocation(
  18. UnsignedBigInteger const& left,
  19. UnsignedBigInteger const& right,
  20. UnsignedBigInteger& temp_shift_result,
  21. UnsignedBigInteger& temp_shift_plus,
  22. UnsignedBigInteger& temp_shift,
  23. UnsignedBigInteger& output)
  24. {
  25. output.set_to_0();
  26. // iterate all bits
  27. for (size_t word_index = 0; word_index < left.length(); ++word_index) {
  28. for (size_t bit_index = 0; bit_index < UnsignedBigInteger::BITS_IN_WORD; ++bit_index) {
  29. // If the bit is off - skip over it
  30. if (!(left.m_words[word_index] & (1 << bit_index)))
  31. continue;
  32. size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  33. // output += (right << shift_amount);
  34. shift_left_without_allocation(right, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  35. add_into_accumulator_without_allocation(output, temp_shift);
  36. }
  37. }
  38. }
  39. }