UnsignedBigInteger.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "UnsignedBigInteger.h"
  27. #include <AK/StringBuilder.h>
  28. namespace Crypto {
  29. UnsignedBigInteger UnsignedBigInteger::create_invalid()
  30. {
  31. UnsignedBigInteger invalid(0);
  32. invalid.invalidate();
  33. return invalid;
  34. }
  35. // FIXME: in great need of optimisation
  36. UnsignedBigInteger UnsignedBigInteger::import_data(const u8* ptr, size_t length)
  37. {
  38. UnsignedBigInteger integer { 0 };
  39. for (size_t i = 0; i < length; ++i) {
  40. auto part = UnsignedBigInteger { ptr[length - i - 1] }.shift_left(8 * i);
  41. integer = integer.plus(part);
  42. }
  43. return integer;
  44. }
  45. size_t UnsignedBigInteger::export_data(AK::ByteBuffer& data) const
  46. {
  47. UnsignedBigInteger copy { *this };
  48. UnsignedBigInteger quotient;
  49. UnsignedBigInteger remainder;
  50. size_t size = trimmed_length() * sizeof(u32);
  51. size_t i = 0;
  52. for (; i < size; ++i) {
  53. if (copy.trimmed_length() == 0)
  54. break;
  55. data[size - i - 1] = copy.m_words[0] & 0xff;
  56. divide_u16_without_allocation(copy, 256, quotient, remainder);
  57. copy.set_to(quotient);
  58. }
  59. return i;
  60. }
  61. UnsignedBigInteger UnsignedBigInteger::from_base10(const String& str)
  62. {
  63. UnsignedBigInteger result;
  64. UnsignedBigInteger ten { 10 };
  65. for (auto& c : str) {
  66. result = result.multiplied_by(ten).plus(c - '0');
  67. }
  68. return result;
  69. }
  70. String UnsignedBigInteger::to_base10() const
  71. {
  72. if (*this == UnsignedBigInteger { 0 })
  73. return "0";
  74. StringBuilder builder;
  75. UnsignedBigInteger temp(*this);
  76. UnsignedBigInteger quotient;
  77. UnsignedBigInteger remainder;
  78. while (temp != UnsignedBigInteger { 0 }) {
  79. divide_u16_without_allocation(temp, 10, quotient, remainder);
  80. ASSERT(remainder.words()[0] < 10);
  81. builder.append(static_cast<char>(remainder.words()[0] + '0'));
  82. temp.set_to(quotient);
  83. }
  84. auto reversed_string = builder.to_string();
  85. builder.clear();
  86. for (int i = reversed_string.length() - 1; i >= 0; --i) {
  87. builder.append(reversed_string[i]);
  88. }
  89. return builder.to_string();
  90. }
  91. void UnsignedBigInteger::set_to_0()
  92. {
  93. m_words.clear_with_capacity();
  94. m_is_invalid = false;
  95. m_cached_trimmed_length = {};
  96. }
  97. void UnsignedBigInteger::set_to(u32 other)
  98. {
  99. m_is_invalid = false;
  100. m_words.resize_and_keep_capacity(1);
  101. m_words[0] = other;
  102. m_cached_trimmed_length = {};
  103. }
  104. void UnsignedBigInteger::set_to(const UnsignedBigInteger& other)
  105. {
  106. m_is_invalid = other.m_is_invalid;
  107. m_words.resize_and_keep_capacity(other.m_words.size());
  108. __builtin_memcpy(m_words.data(), other.m_words.data(), other.m_words.size() * sizeof(u32));
  109. m_cached_trimmed_length = {};
  110. }
  111. size_t UnsignedBigInteger::trimmed_length() const
  112. {
  113. if (!m_cached_trimmed_length.has_value()) {
  114. size_t num_leading_zeroes = 0;
  115. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  116. if (m_words[i] != 0)
  117. break;
  118. }
  119. m_cached_trimmed_length = length() - num_leading_zeroes;
  120. }
  121. return m_cached_trimmed_length.value();
  122. }
  123. FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(const UnsignedBigInteger& other) const
  124. {
  125. UnsignedBigInteger result;
  126. add_without_allocation(*this, other, result);
  127. return result;
  128. }
  129. FLATTEN UnsignedBigInteger UnsignedBigInteger::minus(const UnsignedBigInteger& other) const
  130. {
  131. UnsignedBigInteger result;
  132. subtract_without_allocation(*this, other, result);
  133. return result;
  134. }
  135. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_or(const UnsignedBigInteger& other) const
  136. {
  137. UnsignedBigInteger result;
  138. bitwise_or_without_allocation(*this, other, result);
  139. return result;
  140. }
  141. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_and(const UnsignedBigInteger& other) const
  142. {
  143. UnsignedBigInteger result;
  144. bitwise_and_without_allocation(*this, other, result);
  145. return result;
  146. }
  147. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_xor(const UnsignedBigInteger& other) const
  148. {
  149. UnsignedBigInteger result;
  150. bitwise_xor_without_allocation(*this, other, result);
  151. return result;
  152. }
  153. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_not() const
  154. {
  155. UnsignedBigInteger result;
  156. bitwise_not_without_allocation(*this, result);
  157. return result;
  158. }
  159. FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  160. {
  161. UnsignedBigInteger output;
  162. UnsignedBigInteger temp_result;
  163. UnsignedBigInteger temp_plus;
  164. shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
  165. return output;
  166. }
  167. FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(const UnsignedBigInteger& other) const
  168. {
  169. UnsignedBigInteger result;
  170. UnsignedBigInteger temp_shift_result;
  171. UnsignedBigInteger temp_shift_plus;
  172. UnsignedBigInteger temp_shift;
  173. UnsignedBigInteger temp_plus;
  174. multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, temp_plus, result);
  175. return result;
  176. }
  177. FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(const UnsignedBigInteger& divisor) const
  178. {
  179. UnsignedBigInteger quotient;
  180. UnsignedBigInteger remainder;
  181. // If we actually have a u16-compatible divisor, short-circuit to the
  182. // less computationally-intensive "divide_u16_without_allocation" method.
  183. if (divisor.trimmed_length() == 1 && divisor.m_words[0] < (1 << 16)) {
  184. divide_u16_without_allocation(*this, divisor.m_words[0], quotient, remainder);
  185. return UnsignedDivisionResult { quotient, remainder };
  186. }
  187. UnsignedBigInteger temp_shift_result;
  188. UnsignedBigInteger temp_shift_plus;
  189. UnsignedBigInteger temp_shift;
  190. UnsignedBigInteger temp_minus;
  191. divide_without_allocation(*this, divisor, temp_shift_result, temp_shift_plus, temp_shift, temp_minus, quotient, remainder);
  192. return UnsignedDivisionResult { quotient, remainder };
  193. }
  194. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  195. {
  196. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  197. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  198. m_words.ensure_capacity(word_index);
  199. for (size_t i = length(); i <= word_index; ++i) {
  200. m_words.unchecked_append(0);
  201. }
  202. m_words[word_index] |= (1 << inner_word_index);
  203. m_cached_trimmed_length = {};
  204. }
  205. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  206. {
  207. if (is_invalid() != other.is_invalid())
  208. return false;
  209. auto length = trimmed_length();
  210. if (length != other.trimmed_length())
  211. return false;
  212. return !__builtin_memcmp(m_words.data(), other.words().data(), length);
  213. }
  214. bool UnsignedBigInteger::operator!=(const UnsignedBigInteger& other) const
  215. {
  216. return !(*this == other);
  217. }
  218. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  219. {
  220. auto length = trimmed_length();
  221. auto other_length = other.trimmed_length();
  222. if (length < other_length) {
  223. return true;
  224. }
  225. if (length > other_length) {
  226. return false;
  227. }
  228. if (length == 0) {
  229. return false;
  230. }
  231. for (int i = length - 1; i >= 0; --i) {
  232. if (m_words[i] == other.m_words[i])
  233. continue;
  234. return m_words[i] < other.m_words[i];
  235. }
  236. return false;
  237. }
  238. /**
  239. * Complexity: O(N) where N is the number of words in the larger number
  240. */
  241. void UnsignedBigInteger::add_without_allocation(
  242. const UnsignedBigInteger& left,
  243. const UnsignedBigInteger& right,
  244. UnsignedBigInteger& output)
  245. {
  246. const UnsignedBigInteger* const longer = (left.length() > right.length()) ? &left : &right;
  247. const UnsignedBigInteger* const shorter = (longer == &right) ? &left : &right;
  248. u8 carry = 0;
  249. output.set_to_0();
  250. output.m_words.resize_and_keep_capacity(longer->length());
  251. for (size_t i = 0; i < shorter->length(); ++i) {
  252. u32 word_addition_result = shorter->m_words[i] + longer->m_words[i];
  253. u8 carry_out = 0;
  254. // if there was a carry, the result will be smaller than any of the operands
  255. if (word_addition_result + carry < shorter->m_words[i]) {
  256. carry_out = 1;
  257. }
  258. if (carry) {
  259. word_addition_result++;
  260. }
  261. carry = carry_out;
  262. output.m_words[i] = word_addition_result;
  263. }
  264. for (size_t i = shorter->length(); i < longer->length(); ++i) {
  265. u32 word_addition_result = longer->m_words[i] + carry;
  266. carry = 0;
  267. if (word_addition_result < longer->m_words[i]) {
  268. carry = 1;
  269. }
  270. output.m_words[i] = word_addition_result;
  271. }
  272. if (carry) {
  273. output.m_words.append(carry);
  274. }
  275. }
  276. /**
  277. * Complexity: O(N) where N is the number of words in the larger number
  278. */
  279. void UnsignedBigInteger::subtract_without_allocation(
  280. const UnsignedBigInteger& left,
  281. const UnsignedBigInteger& right,
  282. UnsignedBigInteger& output)
  283. {
  284. if (left < right) {
  285. output.invalidate();
  286. return;
  287. }
  288. u8 borrow = 0;
  289. auto own_length = left.length();
  290. auto other_length = right.length();
  291. output.set_to_0();
  292. output.m_words.resize_and_keep_capacity(own_length);
  293. for (size_t i = 0; i < own_length; ++i) {
  294. u32 other_word = (i < other_length) ? right.m_words[i] : 0;
  295. i64 temp = static_cast<i64>(left.m_words[i]) - static_cast<i64>(other_word) - static_cast<i64>(borrow);
  296. // If temp < 0, we had an underflow
  297. borrow = (temp >= 0) ? 0 : 1;
  298. if (temp < 0) {
  299. temp += (UINT32_MAX + 1);
  300. }
  301. output.m_words[i] = temp;
  302. }
  303. // This assertion should not fail, because we verified that *this>=other at the beginning of the function
  304. ASSERT(borrow == 0);
  305. }
  306. /**
  307. * Complexity: O(N) where N is the number of words in the shorter value
  308. * Method:
  309. * Apply <op> word-wise until words in the shorter value are used up
  310. * then copy the rest of the words verbatim from the longer value.
  311. */
  312. FLATTEN void UnsignedBigInteger::bitwise_or_without_allocation(
  313. const UnsignedBigInteger& left,
  314. const UnsignedBigInteger& right,
  315. UnsignedBigInteger& output)
  316. {
  317. // If either of the BigInts are invalid, the output is just the other one.
  318. if (left.is_invalid()) {
  319. output.set_to(right);
  320. return;
  321. }
  322. if (right.is_invalid()) {
  323. output.set_to(left);
  324. return;
  325. }
  326. const UnsignedBigInteger *shorter, *longer;
  327. if (left.length() < right.length()) {
  328. shorter = &left;
  329. longer = &right;
  330. } else {
  331. shorter = &right;
  332. longer = &left;
  333. }
  334. output.m_words.resize_and_keep_capacity(longer->length());
  335. size_t longer_offset = longer->length() - shorter->length();
  336. for (size_t i = 0; i < shorter->length(); ++i)
  337. output.m_words[i] = longer->words()[i] | shorter->words()[i];
  338. __builtin_memcpy(output.m_words.data() + shorter->length(), longer->words().data() + shorter->length(), sizeof(u32) * longer_offset);
  339. }
  340. /**
  341. * Complexity: O(N) where N is the number of words in the shorter value
  342. * Method:
  343. * Apply 'and' word-wise until words in the shorter value are used up
  344. * and zero the rest.
  345. */
  346. FLATTEN void UnsignedBigInteger::bitwise_and_without_allocation(
  347. const UnsignedBigInteger& left,
  348. const UnsignedBigInteger& right,
  349. UnsignedBigInteger& output)
  350. {
  351. // If either of the BigInts are invalid, the output is just the other one.
  352. if (left.is_invalid()) {
  353. output.set_to(right);
  354. return;
  355. }
  356. if (right.is_invalid()) {
  357. output.set_to(left);
  358. return;
  359. }
  360. const UnsignedBigInteger *shorter, *longer;
  361. if (left.length() < right.length()) {
  362. shorter = &left;
  363. longer = &right;
  364. } else {
  365. shorter = &right;
  366. longer = &left;
  367. }
  368. output.m_words.resize_and_keep_capacity(longer->length());
  369. size_t longer_offset = longer->length() - shorter->length();
  370. for (size_t i = 0; i < shorter->length(); ++i)
  371. output.m_words[i] = longer->words()[i] & shorter->words()[i];
  372. __builtin_memset(output.m_words.data() + shorter->length(), 0, sizeof(u32) * longer_offset);
  373. }
  374. /**
  375. * Complexity: O(N) where N is the number of words in the shorter value
  376. * Method:
  377. * Apply 'xor' word-wise until words in the shorter value are used up
  378. * and copy the rest.
  379. */
  380. FLATTEN void UnsignedBigInteger::bitwise_xor_without_allocation(
  381. const UnsignedBigInteger& left,
  382. const UnsignedBigInteger& right,
  383. UnsignedBigInteger& output)
  384. {
  385. // If either of the BigInts are invalid, the output is just the other one.
  386. if (left.is_invalid()) {
  387. output.set_to(right);
  388. return;
  389. }
  390. if (right.is_invalid()) {
  391. output.set_to(left);
  392. return;
  393. }
  394. const UnsignedBigInteger *shorter, *longer;
  395. if (left.length() < right.length()) {
  396. shorter = &left;
  397. longer = &right;
  398. } else {
  399. shorter = &right;
  400. longer = &left;
  401. }
  402. output.m_words.resize_and_keep_capacity(longer->length());
  403. size_t longer_offset = longer->length() - shorter->length();
  404. for (size_t i = 0; i < shorter->length(); ++i)
  405. output.m_words[i] = longer->words()[i] ^ shorter->words()[i];
  406. __builtin_memcpy(output.m_words.data() + shorter->length(), longer->words().data() + shorter->length(), sizeof(u32) * longer_offset);
  407. }
  408. /**
  409. * Complexity: O(N) where N is the number of words
  410. */
  411. FLATTEN void UnsignedBigInteger::bitwise_not_without_allocation(
  412. const UnsignedBigInteger& right,
  413. UnsignedBigInteger& output)
  414. {
  415. // If the value is invalid, the output value is invalid as well.
  416. if (right.is_invalid()) {
  417. output.invalidate();
  418. return;
  419. }
  420. if (right.length() == 0) {
  421. output.set_to_0();
  422. return;
  423. }
  424. output.m_words.resize_and_keep_capacity(right.length());
  425. if (right.length() > 1) {
  426. for (size_t i = 0; i < right.length() - 1; ++i)
  427. output.m_words[i] = ~right.words()[i];
  428. }
  429. auto last_word_index = right.length() - 1;
  430. auto last_word = right.words()[last_word_index];
  431. output.m_words[last_word_index] = ((u32)0xffffffffffffffff >> __builtin_clz(last_word)) & ~last_word;
  432. }
  433. /**
  434. * Complexity : O(N + num_bits % 8) where N is the number of words in the number
  435. * Shift method :
  436. * Start by shifting by whole words in num_bits (by putting missing words at the start),
  437. * then shift the number's words two by two by the remaining amount of bits.
  438. */
  439. FLATTEN void UnsignedBigInteger::shift_left_without_allocation(
  440. const UnsignedBigInteger& number,
  441. size_t num_bits,
  442. UnsignedBigInteger& temp_result,
  443. UnsignedBigInteger& temp_plus,
  444. UnsignedBigInteger& output)
  445. {
  446. // We can only do shift operations on individual words
  447. // where the shift amount is <= size of word (32).
  448. // But we do know how to shift by a multiple of word size (e.g 64=32*2)
  449. // So we first shift the result by how many whole words fit in 'num_bits'
  450. shift_left_by_n_words(number, num_bits / UnsignedBigInteger::BITS_IN_WORD, temp_result);
  451. output.set_to(temp_result);
  452. // And now we shift by the leftover amount of bits
  453. num_bits %= UnsignedBigInteger::BITS_IN_WORD;
  454. if (num_bits == 0) {
  455. return;
  456. }
  457. for (size_t i = 0; i < temp_result.length(); ++i) {
  458. u32 current_word_of_temp_result = shift_left_get_one_word(temp_result, num_bits, i);
  459. output.m_words[i] = current_word_of_temp_result;
  460. }
  461. // Shifting the last word can produce a carry
  462. u32 carry_word = shift_left_get_one_word(temp_result, num_bits, temp_result.length());
  463. if (carry_word != 0) {
  464. // output += (carry_word << temp_result.length())
  465. // FIXME : Using temp_plus this way to transform carry_word into a bigint is not
  466. // efficient nor pretty. Maybe we should have an "add_with_shift" method ?
  467. temp_plus.set_to_0();
  468. temp_plus.m_words.append(carry_word);
  469. shift_left_by_n_words(temp_plus, temp_result.length(), temp_result);
  470. add_without_allocation(output, temp_result, temp_plus);
  471. output.set_to(temp_plus);
  472. }
  473. }
  474. /**
  475. * Complexity: O(N^2) where N is the number of words in the larger number
  476. * Multiplication method:
  477. * An integer is equal to the sum of the powers of two
  478. * according to the indexes of its 'on' bits.
  479. * So to multiple x*y, we go over each '1' bit in x (say the i'th bit),
  480. * and add y<<i to the result.
  481. */
  482. FLATTEN void UnsignedBigInteger::multiply_without_allocation(
  483. const UnsignedBigInteger& left,
  484. const UnsignedBigInteger& right,
  485. UnsignedBigInteger& temp_shift_result,
  486. UnsignedBigInteger& temp_shift_plus,
  487. UnsignedBigInteger& temp_shift,
  488. UnsignedBigInteger& temp_plus,
  489. UnsignedBigInteger& output)
  490. {
  491. output.set_to_0();
  492. // iterate all bits
  493. for (size_t word_index = 0; word_index < left.length(); ++word_index) {
  494. for (size_t bit_index = 0; bit_index < UnsignedBigInteger::BITS_IN_WORD; ++bit_index) {
  495. // If the bit is off - skip over it
  496. if (!(left.m_words[word_index] & (1 << bit_index)))
  497. continue;
  498. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  499. // output += (right << shift_amount);
  500. shift_left_without_allocation(right, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  501. add_without_allocation(output, temp_shift, temp_plus);
  502. output.set_to(temp_plus);
  503. }
  504. }
  505. }
  506. /**
  507. * Complexity: O(N^2) where N is the number of words in the larger number
  508. * Division method:
  509. * We loop over the bits of the divisor, attempting to subtract divisor<<i from the dividend.
  510. * If the result is non-negative, it means that divisor*2^i "fits" in the dividend,
  511. * so we set the ith bit in the quotient and reduce divisor<<i from the dividend.
  512. * When we're done, what's left from the dividend is the remainder.
  513. */
  514. FLATTEN void UnsignedBigInteger::divide_without_allocation(
  515. const UnsignedBigInteger& numerator,
  516. const UnsignedBigInteger& denominator,
  517. UnsignedBigInteger& temp_shift_result,
  518. UnsignedBigInteger& temp_shift_plus,
  519. UnsignedBigInteger& temp_shift,
  520. UnsignedBigInteger& temp_minus,
  521. UnsignedBigInteger& quotient,
  522. UnsignedBigInteger& remainder)
  523. {
  524. quotient.set_to_0();
  525. remainder.set_to(numerator);
  526. // iterate all bits
  527. for (int word_index = numerator.trimmed_length() - 1; word_index >= 0; --word_index) {
  528. for (int bit_index = UnsignedBigInteger::BITS_IN_WORD - 1; bit_index >= 0; --bit_index) {
  529. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  530. shift_left_without_allocation(denominator, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  531. subtract_without_allocation(remainder, temp_shift, temp_minus);
  532. if (!temp_minus.is_invalid()) {
  533. remainder.set_to(temp_minus);
  534. quotient.set_bit_inplace(shift_amount);
  535. }
  536. }
  537. }
  538. }
  539. /**
  540. * Complexity : O(N) where N is the number of digits in the numerator
  541. * Division method :
  542. * Starting from the most significant one, for each half-word of the numerator, combine it
  543. * with the existing remainder if any, divide the combined number as a u32 operation and
  544. * update the quotient / remainder as needed.
  545. */
  546. FLATTEN void UnsignedBigInteger::divide_u16_without_allocation(
  547. const UnsignedBigInteger& numerator,
  548. u32 denominator,
  549. UnsignedBigInteger& quotient,
  550. UnsignedBigInteger& remainder)
  551. {
  552. ASSERT(denominator < (1 << 16));
  553. u32 remainder_word = 0;
  554. auto numerator_length = numerator.trimmed_length();
  555. quotient.set_to_0();
  556. quotient.m_words.resize(numerator_length);
  557. for (int word_index = numerator_length - 1; word_index >= 0; --word_index) {
  558. auto word_high = numerator.m_words[word_index] >> 16;
  559. auto word_low = numerator.m_words[word_index] & ((1 << 16) - 1);
  560. auto number_to_divide_high = (remainder_word << 16) | word_high;
  561. auto quotient_high = number_to_divide_high / denominator;
  562. remainder_word = number_to_divide_high % denominator;
  563. auto number_to_divide_low = remainder_word << 16 | word_low;
  564. auto quotient_low = number_to_divide_low / denominator;
  565. remainder_word = number_to_divide_low % denominator;
  566. quotient.m_words[word_index] = (quotient_high << 16) | quotient_low;
  567. }
  568. remainder.set_to(remainder_word);
  569. }
  570. ALWAYS_INLINE void UnsignedBigInteger::shift_left_by_n_words(
  571. const UnsignedBigInteger& number,
  572. const size_t number_of_words,
  573. UnsignedBigInteger& output)
  574. {
  575. // shifting left by N words means just inserting N zeroes to the beginning of the words vector
  576. output.set_to_0();
  577. output.m_words.resize_and_keep_capacity(number_of_words + number.length());
  578. __builtin_memset(output.m_words.data(), 0, number_of_words * sizeof(unsigned));
  579. __builtin_memcpy(&output.m_words.data()[number_of_words], number.m_words.data(), number.m_words.size() * sizeof(unsigned));
  580. }
  581. /**
  582. * Returns the word at a requested index in the result of a shift operation
  583. */
  584. ALWAYS_INLINE u32 UnsignedBigInteger::shift_left_get_one_word(
  585. const UnsignedBigInteger& number,
  586. const size_t num_bits,
  587. const size_t result_word_index)
  588. {
  589. // "<= length()" (rather than length() - 1) is intentional,
  590. // The result inedx of length() is used when calculating the carry word
  591. ASSERT(result_word_index <= number.length());
  592. ASSERT(num_bits <= UnsignedBigInteger::BITS_IN_WORD);
  593. u32 result = 0;
  594. // we need to check for "num_bits != 0" since shifting right by 32 is apparently undefined behaviour!
  595. if (result_word_index > 0 && num_bits != 0) {
  596. result += number.m_words[result_word_index - 1] >> (UnsignedBigInteger::BITS_IN_WORD - num_bits);
  597. }
  598. if (result_word_index < number.length() && num_bits < 32) {
  599. result += number.m_words[result_word_index] << num_bits;
  600. }
  601. return result;
  602. }
  603. }