BigIntArithmetic.hx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. /*
  2. * Copyright (C)2005-2023 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package haxe.math.bigint;
  23. import haxe.math.bigint.BigIntException;
  24. import haxe.math.bigint.BigIntError;
  25. import haxe.math.bigint.BigIntHelper;
  26. import haxe.ds.Vector;
  27. /* Original code courtesy Chuck Batson (github.com/cbatson) */
  28. /**
  29. A collection of static helper functions for performing arithmetic
  30. on `BigInt_` objects.
  31. **/
  32. class BigIntArithmetic {
  33. /**
  34. Compare a big integer with an Int.
  35. Returns -1 if `a < b`; otherwise
  36. returns 1 if `a > b`; otherwise
  37. returns 0 (`a == b`).
  38. **/
  39. public static function compareInt(a:BigInt_, b:Int):Int {
  40. if (a.m_count > 1) {
  41. return a.sign();
  42. }
  43. var x:Int = a.m_data.get(0);
  44. var lt:Int = (x - b) ^ ((x ^ b) & ((x - b) ^ x)); // "Hacker's Delight" p. 23
  45. var gt:Int = (b - x) ^ ((x ^ b) & ((b - x) ^ b));
  46. return (lt >> 31) | (gt >>> 31);
  47. }
  48. /**
  49. Compare two big integers.
  50. Returns -1 if `a < b`; otherwise
  51. returns 1 if `a > b`; otherwise
  52. returns 0 (`a == b`).
  53. **/
  54. public static function compare(a:BigInt_, b:BigInt_):Int {
  55. if (a != b) {
  56. var c:Int = (a.sign() & 7) + (b.sign() & 3);
  57. switch (c) {
  58. case 1, 2: // a and b are positive
  59. if (a.m_count > b.m_count) {
  60. return 1;
  61. }
  62. if (a.m_count < b.m_count) {
  63. return -1;
  64. }
  65. case 3, 4: // a is positive, b is negative
  66. return 1;
  67. case 7, 8: // a is negative, b is positive
  68. return -1;
  69. case 10: // a and b are negative
  70. if (a.m_count > b.m_count) {
  71. return -1;
  72. }
  73. if (a.m_count < b.m_count) {
  74. return 1;
  75. }
  76. }
  77. return MultiwordArithmetic.compareUnsigned(a.m_data, b.m_data, a.m_count);
  78. }
  79. return 0;
  80. }
  81. /**
  82. Perform the unary negation of big integer `operand` and put
  83. the result into big integer `result`.
  84. Ok for `result` and `operand` to be the same object.
  85. **/
  86. public static function negate(result:MutableBigInt_, operand:BigInt_):Void {
  87. var c:Int = 1;
  88. var x:Int32 = 0;
  89. var z:Int = 0;
  90. result.ensureCapacity(operand.m_count + 1, result == operand); // overflow may add a digit
  91. for (i in 0...operand.m_count) {
  92. x = ~operand.m_data.get(i);
  93. z = x + c;
  94. result.m_data.set(i, z);
  95. c = (x & ~z) >>> 31; // "Hacker's Delight" p. 38
  96. }
  97. result.m_count = operand.m_count;
  98. // detect overflow; intuitively, this can only occur for inputs of 2 ^ (32 * N - 1).
  99. if ((~x & z) < 0) {
  100. result.m_data.set(result.m_count++, 0);
  101. } else {
  102. // Handle compacting; intuitively, this can only occur for inputs of -[2 ^ (32 * N - 1)].
  103. // TODO: good way to detect this specific scenario?
  104. result.compact();
  105. }
  106. }
  107. /**
  108. Add big integer `operand2` to big integer `operand1` and put
  109. the result into big integer `result`.
  110. Ok for `result`, `operand1`, and `operand2` to be the same object.
  111. **/
  112. public static function add(result:MutableBigInt_, operand1:BigInt_, operand2:BigInt_):Void {
  113. var c:Int = 0;
  114. var x:Int32 = 0, y:Int32 = 0, z:Int = 0;
  115. if (operand1.m_count == operand2.m_count) {
  116. result.ensureCapacity(operand1.m_count + 1, (result == operand1) || (result == operand2));
  117. for (i in 0...operand1.m_count) {
  118. x = operand1.m_data.get(i);
  119. y = operand2.m_data.get(i);
  120. z = x + y + c;
  121. result.m_data.set(i, z);
  122. c = ((x & y) | ((x | y) & ~z)) >>> 31; // "Hacker's Delight" p. 38
  123. }
  124. result.m_count = operand1.m_count;
  125. } else {
  126. // longer operand is put into o1
  127. var o1 = (operand1.m_count > operand2.m_count) ? operand1 : operand2;
  128. var o2 = (operand1.m_count > operand2.m_count) ? operand2 : operand1;
  129. result.ensureCapacity(o1.m_count + 1, (result == operand1) || (result == operand2));
  130. var s:Int = (o2.sign() == -1) ? -1 : 0;
  131. for (i in 0...o2.m_count) {
  132. x = o1.m_data.get(i);
  133. y = o2.m_data.get(i);
  134. z = x + y + c;
  135. result.m_data.set(i, z);
  136. c = ((x & y) | ((x | y) & ~z)) >>> 31; // "Hacker's Delight" p. 38
  137. }
  138. y = s;
  139. for (i in o2.m_count...o1.m_count) {
  140. x = o1.m_data.get(i);
  141. z = x + y + c;
  142. result.m_data.set(i, z);
  143. c = ((x & y) | ((x | y) & ~z)) >>> 31; // "Hacker's Delight" p. 38
  144. }
  145. result.m_count = o1.m_count;
  146. }
  147. var o:Int = (z ^ x) & (z ^ y); // "Hacker's Delight" p. 29
  148. if (o < 0) // overflow flag is in sign bit
  149. {
  150. result.m_data.set(result.m_count++, ~(z >> 31));
  151. } else {
  152. result.compact(); // TODO: True that this will only ever eliminate at most one digit? Lighter way to detect?
  153. }
  154. }
  155. /**
  156. Add integer `operand2` to big integer `operand1` and put the
  157. result into big integer `result`.
  158. Ok for `result` and `operand1` to be the same object.
  159. **/
  160. public static function addInt(result:MutableBigInt_, operand1:BigInt_, operand2:Int):Void {
  161. var c:Int = 0;
  162. var x:Int32;
  163. var y:Int = operand2;
  164. var z:Int;
  165. result.ensureCapacity(operand1.m_count + 1, result == operand1);
  166. if (operand1.m_count > 1) {
  167. x = operand1.m_data.get(0);
  168. z = x + y;
  169. c = ((x & y) | ((x | y) & ~z)) >>> 31; // "Hacker's Delight" p. 38
  170. result.m_data.set(0, z);
  171. y >>= 31;
  172. for (i in 1...operand1.m_count - 1) {
  173. x = operand1.m_data.get(i);
  174. z = x + y + c;
  175. result.m_data.set(i, z);
  176. c = ((x & y) | ((x | y) & ~z)) >>> 31; // "Hacker's Delight" p. 38
  177. }
  178. }
  179. x = operand1.m_data.get(operand1.m_count - 1);
  180. z = x + y + c;
  181. result.m_data.set(operand1.m_count - 1, z);
  182. result.m_count = operand1.m_count;
  183. var o:Int = (z ^ x) & (z ^ y); // "Hacker's Delight" p. 29
  184. if (o < 0) // overflow flag is in sign bit
  185. {
  186. result.m_data.set(result.m_count++, x >> 31);
  187. } else if (result.m_count > 1) {
  188. if (z == (result.m_data.get(result.m_count - 2) >> 31)) {
  189. --result.m_count;
  190. }
  191. }
  192. }
  193. /**
  194. Subtract big integer `operand2` from big integer `operand1`
  195. and put the result into big integer `result`.
  196. Ok for `result`, `operand1`, and `operand2` to be the same object.
  197. **/
  198. public static function subtract(result:MutableBigInt_, operand1:BigInt_, operand2:BigInt_):Void {
  199. var c:Int32 = 0;
  200. var x:Int = 0, y:Int = 0, z:Int = 0;
  201. if (operand1.m_count == operand2.m_count) {
  202. result.ensureCapacity(operand1.m_count + 1, (result == operand1) || (result == operand2));
  203. for (i in 0...operand1.m_count) {
  204. x = operand1.m_data.get(i);
  205. y = operand2.m_data.get(i);
  206. z = x - y - c;
  207. result.m_data.set(i, z);
  208. c = ((~x & y) | (~(x ^ y) & z)) >>> 31; // "Hacker's Delight" p. 38
  209. }
  210. result.m_count = operand1.m_count;
  211. } else if (operand1.m_count > operand2.m_count) {
  212. // operand1 is longer
  213. result.ensureCapacity(operand1.m_count + 1, (result == operand1) || (result == operand2));
  214. var s:Int = (operand2.sign() == -1) ? -1 : 0;
  215. for (i in 0...operand2.m_count) {
  216. x = operand1.m_data.get(i);
  217. y = operand2.m_data.get(i);
  218. z = x - y - c;
  219. result.m_data.set(i, z);
  220. c = ((~x & y) | (~(x ^ y) & z)) >>> 31; // "Hacker's Delight" p. 38
  221. }
  222. y = s;
  223. for (i in operand2.m_count...operand1.m_count) {
  224. x = operand1.m_data.get(i);
  225. z = x - y - c;
  226. result.m_data.set(i, z);
  227. c = ((~x & y) | (~(x ^ y) & z)) >>> 31; // "Hacker's Delight" p. 38
  228. }
  229. result.m_count = operand1.m_count;
  230. } else {
  231. // operand2 is longer
  232. result.ensureCapacity(operand2.m_count + 1, (result == operand1) || (result == operand2));
  233. var s:Int = (operand1.sign() == -1) ? -1 : 0;
  234. for (i in 0...operand1.m_count) {
  235. x = operand1.m_data.get(i);
  236. y = operand2.m_data.get(i);
  237. z = x - y - c;
  238. result.m_data.set(i, z);
  239. c = ((~x & y) | (~(x ^ y) & z)) >>> 31; // "Hacker's Delight" p. 38
  240. }
  241. x = s;
  242. for (i in operand1.m_count...operand2.m_count) {
  243. y = operand2.m_data.get(i);
  244. z = x - y - c;
  245. result.m_data.set(i, z);
  246. c = ((~x & y) | (~(x ^ y) & z)) >>> 31; // "Hacker's Delight" p. 38
  247. }
  248. result.m_count = operand2.m_count;
  249. }
  250. var o:Int = (x ^ y) & (z ^ x); // "Hacker's Delight" p. 29
  251. if (o < 0) // overflow flag is in sign bit
  252. {
  253. result.m_data.set(result.m_count++, ~(z >> 31));
  254. } else {
  255. result.compact(); // TODO: True that this will only ever eliminate at most one digit? Lighter way to detect?
  256. }
  257. }
  258. /**
  259. Subtract integer `operand2` from big integer `operand1` and
  260. put the result into big integer `result`.
  261. Ok for `result` and `operand1` to be the same object.
  262. **/
  263. public static function subtractInt(result:MutableBigInt_, operand1:BigInt_, operand2:Int):Void {
  264. var c:Int = 0;
  265. var x:Int;
  266. var y:Int = operand2;
  267. var z:Int;
  268. result.ensureCapacity(operand1.m_count + 1, result == operand1);
  269. if (operand1.m_count > 1) {
  270. x = operand1.m_data.get(0);
  271. z = x - y;
  272. c = ((~x & y) | (~(x ^ y) & z)) >>> 31; // "Hacker's Delight" p. 38
  273. result.m_data.set(0, z);
  274. y >>= 31;
  275. for (i in 1...operand1.m_count - 1) {
  276. x = operand1.m_data.get(i);
  277. z = x - y - c;
  278. result.m_data.set(i, z);
  279. c = ((~x & y) | (~(x ^ y) & z)) >>> 31; // "Hacker's Delight" p. 38
  280. }
  281. }
  282. x = operand1.m_data.get(operand1.m_count - 1);
  283. z = x - y - c;
  284. result.m_data.set(operand1.m_count - 1, z);
  285. result.m_count = operand1.m_count;
  286. var o:Int = (x ^ y) & (z ^ x); // "Hacker's Delight" p. 29
  287. if (o < 0) // overflow flag is in sign bit
  288. {
  289. result.m_data.set(result.m_count++, x >> 31);
  290. } else if (result.m_count > 1) {
  291. if (z == (result.m_data.get(result.m_count - 2) >> 31)) {
  292. --result.m_count;
  293. }
  294. }
  295. }
  296. /**
  297. Multiply big integer `operand1` by integer `operand2` and put
  298. the result into `result`.
  299. `result` may not refer the same object as either `operand1`
  300. or `operand2`; however, `operand1` and `operand2` may be the
  301. same object.
  302. **/
  303. public static function multiplyInt(result:MutableBigInt_, operand1:BigInt_, operand2:Int):Void {
  304. // TODO: Optimize.
  305. multiply(result, operand1, BigInt_.fromInt(operand2));
  306. }
  307. /**
  308. Multiply big integer `operand1` by big integer `operand2` and
  309. put the result into `result`.
  310. `result` may not refer the same object as either `operand1`
  311. or `operand2`; however, `operand1` and `operand2` may be the
  312. same object.
  313. **/
  314. private static function multiplyTraditional(result:MutableBigInt_, operand1:BigInt_, operand2:BigInt_):Void {
  315. // Implements Figure 8-1 (p. 172) from "Hacker's Delight", Second Edition; Henry S. Warren, Jr.; 2013.
  316. if ((operand1 == result) || (operand2 == result)) {
  317. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  318. }
  319. if (operand1.isZero() || operand2.isZero()) {
  320. result.setFromInt(0);
  321. return;
  322. }
  323. var resultSize:Int = operand1.m_count + operand2.m_count;
  324. result.ensureCapacity(resultSize, false); // always overwrite result
  325. for (i in 0...resultSize) {
  326. result.m_data.set(i, 0);
  327. }
  328. result.m_count = resultSize;
  329. var b:Int, k:Int, t:Int;
  330. var u:Int, v:Int, w:Int;
  331. var m:Int = operand1.m_count << 1;
  332. var n:Int = operand2.m_count << 1;
  333. for (j in 0...n) {
  334. v = operand2.getShort(j);
  335. k = 0;
  336. for (i in 0...m) {
  337. u = operand1.getShort(i);
  338. w = result.getShort(i + j);
  339. t = u * v + w + k;
  340. result.setShort(i + j, t);
  341. k = t >>> 16;
  342. }
  343. result.setShort(j + m, k);
  344. }
  345. // Now result has the unsigned product. Correct by
  346. // subtracting v * 2 ^ (16m) if u < 0, and
  347. // subtracting u * 2 ^ (16n) if v < 0.
  348. // TODO: Do these as 32-bit operations.
  349. if (operand1.isNegative()) {
  350. b = 0;
  351. for (j in 0...n) {
  352. w = result.getShort(j + m);
  353. v = operand2.getShort(j);
  354. t = w - v - b;
  355. result.setShort(j + m, t);
  356. b = t >>> 31;
  357. }
  358. }
  359. if (operand2.isNegative()) {
  360. b = 0;
  361. for (i in 0...m) {
  362. w = result.getShort(i + n);
  363. u = operand1.getShort(i);
  364. t = w - u - b;
  365. result.setShort(i + n, t);
  366. b = t >>> 31;
  367. }
  368. }
  369. result.compact();
  370. }
  371. /**
  372. Divide the big integer `dividend` by the integer `divisor`.
  373. The quotient of the division is put into `quotientOut`;
  374. the remainder is the return value.
  375. `quotientOut` may refer to `dividend`.
  376. `work`, if supplied, must not refer to any of the inputs.
  377. **/
  378. public static function divideInt(dividend:BigInt_, divisor:Int, quotientOut:MutableBigInt_, work:MutableBigInt_ = null):Int {
  379. // TODO: Consider optimizing this case.
  380. var remainder = new MutableBigInt_();
  381. var divisorBi = BigInt_.fromInt(divisor);
  382. divide(dividend, divisorBi, quotientOut, remainder, work);
  383. return remainder.m_data.get(0);
  384. }
  385. /**
  386. Divide the big integer `dividend` by the big integer `divisor`.
  387. The quotient of the division is put into `quotientOut`;
  388. the remainder is put into `remainderOut`.
  389. `remainderOut` may be `null` if the remainder value is not
  390. needed.
  391. `dividend` and `divisor` may refer to the same object.
  392. `quotientOut` and `remainderOut` must not refer to the same
  393. object; but either may refer to the inputs.
  394. `work`, if supplied, must not refer to any of the inputs.
  395. **/
  396. public static function divide(dividend:BigInt_, divisor:BigInt_, quotientOut:MutableBigInt_, remainderOut:MutableBigInt_,
  397. work:MutableBigInt_ = null):Void {
  398. var dividendSign = dividend.sign();
  399. var divisorSign = divisor.sign();
  400. // Create a combined case value: 0 = both positive, 1 = dividend positive/divisor negative,
  401. // 2 = dividend negative/divisor positive, 3 = both negative
  402. var c:Int = 0;
  403. if (dividendSign == -1)
  404. c += 2;
  405. if (divisorSign == -1)
  406. c += 1;
  407. switch (c) {
  408. case 0: // dividend positive, divisor positive
  409. multiwordUnsignedDivide(dividend, divisor, quotientOut, remainderOut, work);
  410. case 1: // dividend positive, divisor negative
  411. negate(quotientOut, divisor);
  412. multiwordUnsignedDivide(dividend, quotientOut, quotientOut, remainderOut, work);
  413. negate(quotientOut, quotientOut);
  414. case 2: // dividend negative, divisor positive
  415. negate(quotientOut, dividend);
  416. multiwordUnsignedDivide(quotientOut, divisor, quotientOut, remainderOut, work);
  417. negate(quotientOut, quotientOut);
  418. if (remainderOut != null) {
  419. negate(remainderOut, remainderOut);
  420. }
  421. case 3: // dividend negative, divisor negative
  422. if (remainderOut == null) {
  423. // TODO: use work buffer rather than creating an object here
  424. remainderOut = new MutableBigInt_();
  425. }
  426. negate(quotientOut, dividend);
  427. negate(remainderOut, divisor);
  428. multiwordUnsignedDivide(quotientOut, remainderOut, quotientOut, remainderOut, work);
  429. negate(remainderOut, remainderOut);
  430. }
  431. }
  432. /*
  433. Unsigned division; inputs must not be negative.
  434. `remainderOut` may be `null` if the remainder value is not
  435. needed.
  436. `dividend` and `divisor` may refer to the same object.
  437. `quotientOut` and `remainderOut` must not refer to the same
  438. object; but either may refer to the inputs.
  439. `work`, if supplied, must not refer to any of the inputs.
  440. */
  441. private static function multiwordUnsignedDivide(dividend:BigInt_, divisor:BigInt_, quotientOut:MutableBigInt_, remainderOut:MutableBigInt_,
  442. work:MutableBigInt_ = null):Void {
  443. if ((quotientOut == null) || (dividend == null) || (divisor == null)) {
  444. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  445. }
  446. if ((work == dividend) || (work == divisor) || (work == quotientOut)) {
  447. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  448. }
  449. var dividendInts:Int = dividend.getUnsignedDigitCount();
  450. var divisorInts:Int = divisor.getUnsignedDigitCount();
  451. var quotientLength:Int = MultiwordArithmetic.getDivisionQuotientLengthUnsigned(dividendInts, divisorInts);
  452. if (remainderOut != null) {
  453. if (work == remainderOut) {
  454. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  455. }
  456. remainderOut.ensureCapacity(divisor.m_count, (remainderOut == dividend) || (remainderOut == divisor));
  457. }
  458. quotientOut.ensureCapacity(quotientLength + 1, (quotientOut == dividend) || (quotientOut == divisor)); // +1 in case we need leading 0 digit
  459. if (work == null) {
  460. work = new MutableBigInt_();
  461. }
  462. work.ensureCapacity(dividendInts + divisorInts + 1, false);
  463. MultiwordArithmetic.divideUnsigned(dividend.m_data, dividendInts, divisor.m_data, divisorInts, quotientOut.m_data,
  464. (remainderOut != null) ? remainderOut.m_data : null, work.m_data);
  465. quotientOut.m_count = quotientLength;
  466. if (quotientOut.isNegative()) {
  467. quotientOut.m_data.set(quotientOut.m_count++, 0);
  468. } else {
  469. quotientOut.compact();
  470. }
  471. if (remainderOut != null) {
  472. remainderOut.m_count = divisorInts;
  473. if (remainderOut.isNegative()) {
  474. remainderOut.m_data.set(remainderOut.m_count++, 0);
  475. } else {
  476. remainderOut.compact();
  477. }
  478. }
  479. }
  480. /**
  481. Shift big integer `operand1` to the left by `operand2` bits
  482. and put the result into big integer `result`.
  483. Ok for `result` and `operand1` to be the same object.
  484. **/
  485. public static function arithmeticShiftLeft(result:MutableBigInt_, operand1:BigInt_, operand2:Int):Void {
  486. if (operand2 < 0) {
  487. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  488. }
  489. if ((operand2 == 0) || operand1.isZero()) {
  490. result.copyFrom(operand1);
  491. return;
  492. }
  493. result.ensureCapacity(operand1.m_count + ((operand2 + 31) >> 5), result == operand1);
  494. var whole:Int = operand2 >> 5; // whole digits portion
  495. var n:Int = operand2 & 0x1f; // sub digit poortion
  496. if (n > 0) {
  497. asl32(result.m_data, whole, operand1.m_data, operand1.m_count, n);
  498. result.m_count = operand1.m_count + whole + 1;
  499. result.compact();
  500. } else if (whole > 0) {
  501. for (i in 0...operand1.m_count) {
  502. result.m_data.set(operand1.m_count - i - 1 + whole, operand1.m_data.get(operand1.m_count - i - 1));
  503. }
  504. result.m_count = operand1.m_count + whole;
  505. }
  506. for (i in 0...whole) {
  507. result.m_data.set(i, 0);
  508. }
  509. }
  510. /**
  511. Shift big integer `operand1` to the right by `operand2` bits
  512. and put the result into big integer `result`.
  513. Ok for `result` and `operand1` to be the same object.
  514. **/
  515. public static function arithmeticShiftRight(result:MutableBigInt_, operand1:BigInt_, operand2:Int):Void {
  516. if (operand2 < 0) {
  517. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  518. }
  519. if ((operand2 == 0) || operand1.isZero()) {
  520. result.copyFrom(operand1);
  521. return;
  522. }
  523. result.ensureCapacity(operand1.m_count, result == operand1);
  524. var whole:Int = operand2 >> 5; // whole digits portion
  525. var n:Int = operand2 & 0x1f; // sub digit poortion
  526. if (whole >= operand1.m_count) {
  527. result.m_data.set(0, (operand1.sign() == -1) ? -1 : 0);
  528. result.m_count = 1;
  529. } else if (n > 0) {
  530. MultiwordArithmetic._asr32(result.m_data, operand1.m_data, operand1.m_count, whole, n);
  531. result.m_count = operand1.m_count - whole;
  532. result.compact();
  533. } else if (whole > 0) {
  534. for (i in 0...operand1.m_count - whole) {
  535. result.m_data.set(i, operand1.m_data.get(i + whole));
  536. }
  537. result.m_count = operand1.m_count - whole;
  538. }
  539. }
  540. /**
  541. Returns the value, 0 or 1, of the bit at 2^`index` place.
  542. **/
  543. public static inline function getBit(value:BigInt_, index:Int):Int {
  544. return MultiwordArithmetic.getBitSigned(value.m_data, value.m_count, index);
  545. }
  546. /**
  547. Returns the bitwise AND of `operand1` with `operand2`.
  548. **/
  549. public static inline function bitwiseAndInt(operand1:BigInt_, operand2:Int):Int {
  550. return operand1.m_data.get(0) & operand2;
  551. }
  552. /**
  553. Returns the bitwise AND of two big integers.
  554. @return A new `BigInt_` holding the result.
  555. **/
  556. public static inline function bitwiseAnd(operand1:BigInt_, operand2:BigInt_):BigInt_ {
  557. var result:MutableBigInt_ = new MutableBigInt_();
  558. if ((operand1.m_count > operand2.m_count)) {
  559. result.m_count = (operand2.sign() == 1) ? operand2.m_count : operand1.m_count;
  560. } else {
  561. result.m_count = (operand1.sign() == 1) ? operand1.m_count : operand2.m_count;
  562. }
  563. result.ensureCapacity(result.m_count, false);
  564. for (i in 0...result.m_count) {
  565. if (i > (operand1.m_count - 1)) {
  566. result.m_data.set(i, operand2.m_data.get(i));
  567. } else if (i > (operand2.m_count - 1)) {
  568. result.m_data.set(i, operand1.m_data.get(i));
  569. } else {
  570. result.m_data.set(i, (operand1.m_data.get(i) & operand2.m_data.get(i)));
  571. }
  572. }
  573. result.compact();
  574. return result;
  575. }
  576. /**
  577. Returns the bitwise OR of `operand1` with `operand2`.
  578. **/
  579. public static inline function bitwiseOr(operand1:BigInt_, operand2:BigInt_):BigInt_ {
  580. var result:MutableBigInt_ = new MutableBigInt_();
  581. result.m_count = (operand1.m_count > operand2.m_count) ? operand1.m_count : operand2.m_count;
  582. result.ensureCapacity(result.m_count, false);
  583. var operand1Positive:Bool = operand1.sign() == 1;
  584. var operand2Positive:Bool = operand2.sign() == 1;
  585. for (i in 0...result.m_count) {
  586. if (i > (operand1.m_count - 1)) {
  587. result.m_data.set(i, (operand1Positive ? operand2.m_data.get(i) : 0xffffffff));
  588. } else if (i > (operand2.m_count - 1)) {
  589. result.m_data.set(i, (operand2Positive ? operand1.m_data.get(i) : 0xffffffff));
  590. } else {
  591. result.m_data.set(i, (operand1.m_data.get(i) | operand2.m_data.get(i)));
  592. }
  593. }
  594. result.compact();
  595. return result;
  596. }
  597. /**
  598. Returns the bitwise XOR of two big integers.
  599. @return A new `BigInt_` holding the result.
  600. **/
  601. public static inline function bitwiseXor(operand1:BigInt_, operand2:BigInt_):BigInt_ {
  602. var result:MutableBigInt_ = new MutableBigInt_();
  603. result.m_count = (operand1.m_count > operand2.m_count) ? operand1.m_count : operand2.m_count;
  604. result.ensureCapacity(result.m_count, false);
  605. var operand1Positive:Bool = operand1.sign() == 1;
  606. var operand2Positive:Bool = operand2.sign() == 1;
  607. for (i in 0...result.m_count) {
  608. if (i > (operand1.m_count - 1)) {
  609. result.m_data.set(i, (operand1Positive ? operand2.m_data.get(i) : (operand2.m_data.get(i) ^ 0xffffffff)));
  610. } else if (i > (operand2.m_count - 1)) {
  611. result.m_data.set(i, (operand2Positive ? operand1.m_data.get(i) : (operand1.m_data.get(i) ^ 0xffffffff)));
  612. } else {
  613. result.m_data.set(i, (operand1.m_data.get(i) ^ operand2.m_data.get(i)));
  614. }
  615. }
  616. result.compact();
  617. return result;
  618. }
  619. /**
  620. Returns the bitwise NOT (inversion) of a big integer.
  621. @return A new `BigInt_` holding the result.
  622. **/
  623. public static inline function bitwiseNot(operand:BigInt_):BigInt_ {
  624. var result:MutableBigInt_ = new MutableBigInt_();
  625. result.copyFrom(operand);
  626. for (i in 0...result.m_count) {
  627. result.m_data.set(i, ~operand.m_data.get(i));
  628. }
  629. result.compact();
  630. return result;
  631. }
  632. /**
  633. Returns `floor(log2(input))`.
  634. @param input The `BigInt_` operand.
  635. @return The integer base-2 logarithm.
  636. **/
  637. public static function floorLog2(input:BigInt_):Int {
  638. return (input.m_count << 5) - BigIntHelper.nlz(input.m_data.get(input.m_count - 1));
  639. }
  640. //-----------------------------------------------------------------------
  641. // Private helpers
  642. //-----------------------------------------------------------------------
  643. // assumes 0 < shift < 32
  644. // ok if output == input
  645. private static inline function asl32(output:Vector<Int>, outputOffset:Int, input:Vector<Int>, inputSize:Int, shift:Int32):Void {
  646. var x:Int = input.get(inputSize - 1) >> 31; // sign extend
  647. var r:Int = 32 - shift;
  648. var y:Int;
  649. while (inputSize > 0) {
  650. y = input[inputSize - 1];
  651. x = (x << shift) | (y >>> r);
  652. output.set(inputSize + outputOffset, x);
  653. x = y;
  654. --inputSize;
  655. }
  656. output.set(outputOffset, x << shift);
  657. }
  658. // assumes 0 < shift < 32
  659. // ok if output == input
  660. private static inline function lsl32(output:Vector<Int>, outputOffset:Int, input:Vector<Int>, inputSize:Int, shift:Int32):Void {
  661. var x:Int = 0;
  662. var r:Int = 32 - shift;
  663. var y:Int;
  664. while (inputSize > 0) {
  665. y = input[inputSize - 1];
  666. x = (x << shift) | (y >>> r);
  667. output.set(inputSize + outputOffset, x);
  668. x = y;
  669. --inputSize;
  670. }
  671. output.set(outputOffset, x << shift);
  672. }
  673. // assumes 0 < shift < 32
  674. // ok if output == input
  675. private static inline function lsr32(output:Vector<Int>, input:Vector<Int>, inputSize:Int, inputOffset:Int, shift:Int32):Void {
  676. var r:Int = 32 - shift;
  677. var i:Int = 0;
  678. while (i < inputSize - 1) {
  679. output.set(i, (input.get(inputOffset + i) >>> shift) | (input.get(inputOffset + i + 1) << r));
  680. ++i;
  681. }
  682. output.set(i, input.get(inputOffset + i) >>> shift);
  683. }
  684. private static inline function copy(output:Vector<Int>, outputOffset:Int, input:Vector<Int>, inputOffset:Int, length:Int):Void {
  685. for (i in 0...length) {
  686. output.set(outputOffset + i, input.get(inputOffset + i));
  687. }
  688. }
  689. private static function nextPowerOfTwo(value:Int):Int {
  690. if (value <= 0)
  691. return 1;
  692. value--;
  693. value |= value >> 1;
  694. value |= value >> 2;
  695. value |= value >> 4;
  696. value |= value >> 8;
  697. value |= value >> 16;
  698. return value + 1;
  699. }
  700. private static function splitAtPowerOfTwo(value:BigInt_, splitBits:Int, high:MutableBigInt_, low:MutableBigInt_):Void {
  701. if (splitBits <= 0) {
  702. high.setFromInt(0);
  703. low.copyFrom(value);
  704. return;
  705. }
  706. var wordBoundary:Int = splitBits >> 5;
  707. var bitOffset:Int = splitBits & 0x1f; // modulo 32
  708. if (wordBoundary >= value.m_count) {
  709. high.setFromInt(0);
  710. low.copyFrom(value);
  711. return;
  712. }
  713. low.ensureCapacity(wordBoundary + 1, false);
  714. // Copy the lower words
  715. for (i in 0...wordBoundary) {
  716. low.m_data.set(i, value.m_data.get(i));
  717. }
  718. if (bitOffset > 0 && wordBoundary < value.m_count) {
  719. var mask:Int = (1 << bitOffset) - 1;
  720. low.m_data.set(wordBoundary, value.m_data.get(wordBoundary) & mask);
  721. low.m_count = wordBoundary + 1;
  722. } else {
  723. low.m_count = wordBoundary;
  724. }
  725. // Ensure low part is always treated as positive
  726. // by adding a leading zero if the most significant bit is set
  727. if (low.m_count > 0 && low.m_data.get(low.m_count - 1) < 0) {
  728. low.ensureCapacity(low.m_count + 1, false);
  729. low.m_data.set(low.m_count, 0);
  730. low.m_count++;
  731. }
  732. low.compact();
  733. BigIntArithmetic.arithmeticShiftRight(high, value, splitBits);
  734. }
  735. public static function multiply(result:MutableBigInt_, operand1:BigInt_, operand2:BigInt_):Void {
  736. if ((operand1 == result) || (operand2 == result)) {
  737. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  738. }
  739. if (operand1.isZero() || operand2.isZero()) {
  740. result.setFromInt(0);
  741. return;
  742. }
  743. var bitLength1 = operand1.bitLength();
  744. var bitLength2 = operand2.bitLength();
  745. if (bitLength1 < 512 || bitLength2 < 512) {
  746. BigIntArithmetic.multiplyTraditional(result, operand1, operand2);
  747. return;
  748. }
  749. var maxBits = (bitLength1 > bitLength2) ? bitLength1 : bitLength2;
  750. var splitBits = nextPowerOfTwo(maxBits >> 1);
  751. if (splitBits < 256)
  752. splitBits = 256;
  753. multiplyKaratsuba(result, operand1, operand2, splitBits);
  754. }
  755. private static function multiplyKaratsuba(result:MutableBigInt_, x:BigInt_, y:BigInt_, splitBits:Int):Void {
  756. if (x.bitLength() < 512 || y.bitLength() < 512) {
  757. BigIntArithmetic.multiplyTraditional(result, x, y);
  758. return;
  759. }
  760. var x1 = new MutableBigInt_();
  761. var x0 = new MutableBigInt_();
  762. splitAtPowerOfTwo(x, splitBits, x1, x0);
  763. var y1 = new MutableBigInt_();
  764. var y0 = new MutableBigInt_();
  765. splitAtPowerOfTwo(y, splitBits, y1, y0);
  766. var z2 = new MutableBigInt_(); // x1 * y1
  767. var z0 = new MutableBigInt_(); // x0 * y0
  768. var z1 = new MutableBigInt_(); // (x1 + x0) * (y1 + y0) - z2 - z0
  769. // z2 = x1 * y1
  770. multiplyKaratsuba(z2, x1, y1, splitBits >> 1);
  771. // z0 = x0 * y0
  772. multiplyKaratsuba(z0, x0, y0, splitBits >> 1);
  773. // z1 = (x1 + x0) * (y1 + y0) - z2 - z0
  774. var sum_x = new MutableBigInt_();
  775. var sum_y = new MutableBigInt_();
  776. BigIntArithmetic.add(sum_x, x1, x0);
  777. BigIntArithmetic.add(sum_y, y1, y0);
  778. multiplyKaratsuba(z1, sum_x, sum_y, splitBits >> 1);
  779. BigIntArithmetic.subtract(z1, z1, z2);
  780. BigIntArithmetic.subtract(z1, z1, z0);
  781. // result = z2 * 2^(2*splitBits) + z1 * 2^splitBits + z0
  782. var temp1 = new MutableBigInt_();
  783. var temp2 = new MutableBigInt_();
  784. // z2 * 2^(2*splitBits)
  785. BigIntArithmetic.arithmeticShiftLeft(temp1, z2, 2 * splitBits);
  786. // z1 * 2^splitBits
  787. BigIntArithmetic.arithmeticShiftLeft(temp2, z1, splitBits);
  788. BigIntArithmetic.add(result, temp1, temp2);
  789. BigIntArithmetic.add(result, result, z0);
  790. }
  791. /**
  792. Squaring operation using power-of-two splitting.
  793. @param result The output BigInt for the square
  794. @param operand The operand to square
  795. **/
  796. public static function square(result:MutableBigInt_, operand:BigInt_):Void {
  797. if (operand == result) {
  798. throw new BigIntException(BigIntError.INVALID_ARGUMENT);
  799. }
  800. if (operand.isZero()) {
  801. result.setFromInt(0);
  802. return;
  803. }
  804. var bitLength = operand.bitLength();
  805. if (bitLength < 512) {
  806. BigIntArithmetic.multiplyTraditional(result, operand, operand);
  807. return;
  808. }
  809. var splitBits = nextPowerOfTwo(bitLength >> 1);
  810. if (splitBits < 256)
  811. splitBits = 256;
  812. var high = new MutableBigInt_();
  813. var low = new MutableBigInt_();
  814. splitAtPowerOfTwo(operand, splitBits, high, low);
  815. // Calculate (high + low)^2 = high^2 + 2*high*low + low^2
  816. var highSquared = new MutableBigInt_();
  817. var lowSquared = new MutableBigInt_();
  818. var crossProduct = new MutableBigInt_();
  819. square(highSquared, high);
  820. square(lowSquared, low);
  821. // Calculate 2 * high * low
  822. multiplyKaratsuba(crossProduct, high, low, splitBits >> 1);
  823. BigIntArithmetic.arithmeticShiftLeft(crossProduct, crossProduct, 1);
  824. // Combine results: result = high^2 * 2^(2*splitBits) + 2*high*low * 2^splitBits + low^2
  825. var temp1 = new MutableBigInt_();
  826. var temp2 = new MutableBigInt_();
  827. BigIntArithmetic.arithmeticShiftLeft(temp1, highSquared, 2 * splitBits);
  828. BigIntArithmetic.arithmeticShiftLeft(temp2, crossProduct, splitBits);
  829. BigIntArithmetic.add(result, temp1, temp2);
  830. BigIntArithmetic.add(result, result, lowSquared);
  831. }
  832. }