UnsignedBigInteger.cpp 23 KB

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