juce_BigInteger.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. namespace
  22. {
  23. inline size_t bitToIndex (const int bit) noexcept { return (size_t) (bit >> 5); }
  24. inline uint32 bitToMask (const int bit) noexcept { return (uint32) 1 << (bit & 31); }
  25. }
  26. //==============================================================================
  27. BigInteger::BigInteger()
  28. : numValues (4),
  29. highestBit (-1),
  30. negative (false)
  31. {
  32. values.calloc (numValues + 1);
  33. }
  34. BigInteger::BigInteger (const int32 value)
  35. : numValues (4),
  36. highestBit (31),
  37. negative (value < 0)
  38. {
  39. values.calloc (numValues + 1);
  40. values[0] = (uint32) std::abs (value);
  41. highestBit = getHighestBit();
  42. }
  43. BigInteger::BigInteger (const uint32 value)
  44. : numValues (4),
  45. highestBit (31),
  46. negative (false)
  47. {
  48. values.calloc (numValues + 1);
  49. values[0] = value;
  50. highestBit = getHighestBit();
  51. }
  52. BigInteger::BigInteger (int64 value)
  53. : numValues (4),
  54. highestBit (63),
  55. negative (value < 0)
  56. {
  57. values.calloc (numValues + 1);
  58. if (value < 0)
  59. value = -value;
  60. values[0] = (uint32) value;
  61. values[1] = (uint32) (value >> 32);
  62. highestBit = getHighestBit();
  63. }
  64. BigInteger::BigInteger (const BigInteger& other)
  65. : numValues ((size_t) jmax ((size_t) 4, bitToIndex (other.highestBit) + 1)),
  66. highestBit (other.getHighestBit()),
  67. negative (other.negative)
  68. {
  69. values.malloc (numValues + 1);
  70. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  71. }
  72. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  73. BigInteger::BigInteger (BigInteger&& other) noexcept
  74. : values (static_cast<HeapBlock<uint32>&&> (other.values)),
  75. numValues (other.numValues),
  76. highestBit (other.highestBit),
  77. negative (other.negative)
  78. {
  79. }
  80. BigInteger& BigInteger::operator= (BigInteger&& other) noexcept
  81. {
  82. values = static_cast<HeapBlock<uint32>&&> (other.values);
  83. numValues = other.numValues;
  84. highestBit = other.highestBit;
  85. negative = other.negative;
  86. return *this;
  87. }
  88. #endif
  89. BigInteger::~BigInteger()
  90. {
  91. }
  92. void BigInteger::swapWith (BigInteger& other) noexcept
  93. {
  94. values.swapWith (other.values);
  95. std::swap (numValues, other.numValues);
  96. std::swap (highestBit, other.highestBit);
  97. std::swap (negative, other.negative);
  98. }
  99. BigInteger& BigInteger::operator= (const BigInteger& other)
  100. {
  101. if (this != &other)
  102. {
  103. highestBit = other.getHighestBit();
  104. jassert (other.numValues >= 4);
  105. numValues = (size_t) jmax ((size_t) 4, bitToIndex (highestBit) + 1);
  106. negative = other.negative;
  107. values.malloc (numValues + 1);
  108. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  109. }
  110. return *this;
  111. }
  112. void BigInteger::ensureSize (const size_t numVals)
  113. {
  114. if (numVals + 2 >= numValues)
  115. {
  116. size_t oldSize = numValues;
  117. numValues = ((numVals + 2) * 3) / 2;
  118. values.realloc (numValues + 1);
  119. while (oldSize < numValues)
  120. values [oldSize++] = 0;
  121. }
  122. }
  123. //==============================================================================
  124. bool BigInteger::operator[] (const int bit) const noexcept
  125. {
  126. return bit <= highestBit && bit >= 0
  127. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  128. }
  129. int BigInteger::toInteger() const noexcept
  130. {
  131. const int n = (int) (values[0] & 0x7fffffff);
  132. return negative ? -n : n;
  133. }
  134. int64 BigInteger::toInt64() const noexcept
  135. {
  136. const int64 n = (((int64) (values[1] & 0x7fffffff)) << 32) | values[0];
  137. return negative ? -n : n;
  138. }
  139. BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  140. {
  141. BigInteger r;
  142. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  143. r.ensureSize ((size_t) bitToIndex (numBits));
  144. r.highestBit = numBits;
  145. int i = 0;
  146. while (numBits > 0)
  147. {
  148. r.values[i++] = getBitRangeAsInt (startBit, (int) jmin (32, numBits));
  149. numBits -= 32;
  150. startBit += 32;
  151. }
  152. r.highestBit = r.getHighestBit();
  153. return r;
  154. }
  155. uint32 BigInteger::getBitRangeAsInt (const int startBit, int numBits) const noexcept
  156. {
  157. if (numBits > 32)
  158. {
  159. jassertfalse; // use getBitRange() if you need more than 32 bits..
  160. numBits = 32;
  161. }
  162. numBits = jmin (numBits, highestBit + 1 - startBit);
  163. if (numBits <= 0)
  164. return 0;
  165. const size_t pos = bitToIndex (startBit);
  166. const int offset = startBit & 31;
  167. const int endSpace = 32 - numBits;
  168. uint32 n = ((uint32) values [pos]) >> offset;
  169. if (offset > endSpace)
  170. n |= ((uint32) values [pos + 1]) << (32 - offset);
  171. return n & (((uint32) 0xffffffff) >> endSpace);
  172. }
  173. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  174. {
  175. if (numBits > 32)
  176. {
  177. jassertfalse;
  178. numBits = 32;
  179. }
  180. for (int i = 0; i < numBits; ++i)
  181. {
  182. setBit (startBit + i, (valueToSet & 1) != 0);
  183. valueToSet >>= 1;
  184. }
  185. }
  186. //==============================================================================
  187. void BigInteger::clear()
  188. {
  189. if (numValues > 16)
  190. {
  191. numValues = 4;
  192. values.calloc (numValues + 1);
  193. }
  194. else
  195. {
  196. values.clear (numValues + 1);
  197. }
  198. highestBit = -1;
  199. negative = false;
  200. }
  201. void BigInteger::setBit (const int bit)
  202. {
  203. if (bit >= 0)
  204. {
  205. if (bit > highestBit)
  206. {
  207. ensureSize (bitToIndex (bit));
  208. highestBit = bit;
  209. }
  210. values [bitToIndex (bit)] |= bitToMask (bit);
  211. }
  212. }
  213. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  214. {
  215. if (shouldBeSet)
  216. setBit (bit);
  217. else
  218. clearBit (bit);
  219. }
  220. void BigInteger::clearBit (const int bit) noexcept
  221. {
  222. if (bit >= 0 && bit <= highestBit)
  223. values [bitToIndex (bit)] &= ~bitToMask (bit);
  224. }
  225. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  226. {
  227. while (--numBits >= 0)
  228. setBit (startBit++, shouldBeSet);
  229. }
  230. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  231. {
  232. if (bit >= 0)
  233. shiftBits (1, bit);
  234. setBit (bit, shouldBeSet);
  235. }
  236. //==============================================================================
  237. bool BigInteger::isZero() const noexcept
  238. {
  239. return getHighestBit() < 0;
  240. }
  241. bool BigInteger::isOne() const noexcept
  242. {
  243. return getHighestBit() == 0 && ! negative;
  244. }
  245. bool BigInteger::isNegative() const noexcept
  246. {
  247. return negative && ! isZero();
  248. }
  249. void BigInteger::setNegative (const bool neg) noexcept
  250. {
  251. negative = neg;
  252. }
  253. void BigInteger::negate() noexcept
  254. {
  255. negative = (! negative) && ! isZero();
  256. }
  257. #if JUCE_MSVC && ! defined (__INTEL_COMPILER)
  258. #pragma intrinsic (_BitScanReverse)
  259. #endif
  260. inline static int highestBitInInt (uint32 n) noexcept
  261. {
  262. jassert (n != 0); // (the built-in functions may not work for n = 0)
  263. #if JUCE_GCC || JUCE_CLANG
  264. return 31 - __builtin_clz (n);
  265. #elif JUCE_MSVC
  266. unsigned long highest;
  267. _BitScanReverse (&highest, n);
  268. return (int) highest;
  269. #else
  270. n |= (n >> 1);
  271. n |= (n >> 2);
  272. n |= (n >> 4);
  273. n |= (n >> 8);
  274. n |= (n >> 16);
  275. return countBitsInInt32 (n >> 1);
  276. #endif
  277. }
  278. int BigInteger::countNumberOfSetBits() const noexcept
  279. {
  280. int total = 0;
  281. for (int i = (int) bitToIndex (highestBit) + 1; --i >= 0;)
  282. total += countNumberOfBits (values[i]);
  283. return total;
  284. }
  285. int BigInteger::getHighestBit() const noexcept
  286. {
  287. for (int i = (int) bitToIndex (highestBit + 1); i >= 0; --i)
  288. {
  289. const uint32 n = values[i];
  290. if (n != 0)
  291. return highestBitInInt (n) + (i << 5);
  292. }
  293. return -1;
  294. }
  295. int BigInteger::findNextSetBit (int i) const noexcept
  296. {
  297. for (; i <= highestBit; ++i)
  298. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  299. return i;
  300. return -1;
  301. }
  302. int BigInteger::findNextClearBit (int i) const noexcept
  303. {
  304. for (; i <= highestBit; ++i)
  305. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  306. break;
  307. return i;
  308. }
  309. //==============================================================================
  310. BigInteger& BigInteger::operator+= (const BigInteger& other)
  311. {
  312. if (other.isNegative())
  313. return operator-= (-other);
  314. if (isNegative())
  315. {
  316. if (compareAbsolute (other) < 0)
  317. {
  318. BigInteger temp (*this);
  319. temp.negate();
  320. *this = other;
  321. operator-= (temp);
  322. }
  323. else
  324. {
  325. negate();
  326. operator-= (other);
  327. negate();
  328. }
  329. }
  330. else
  331. {
  332. if (other.highestBit > highestBit)
  333. highestBit = other.highestBit;
  334. ++highestBit;
  335. const size_t numInts = bitToIndex (highestBit) + 1;
  336. ensureSize (numInts);
  337. int64 remainder = 0;
  338. for (size_t i = 0; i <= numInts; ++i)
  339. {
  340. if (i < numValues)
  341. remainder += values[i];
  342. if (i < other.numValues)
  343. remainder += other.values[i];
  344. values[i] = (uint32) remainder;
  345. remainder >>= 32;
  346. }
  347. jassert (remainder == 0);
  348. highestBit = getHighestBit();
  349. }
  350. return *this;
  351. }
  352. BigInteger& BigInteger::operator-= (const BigInteger& other)
  353. {
  354. if (other.isNegative())
  355. return operator+= (-other);
  356. if (! isNegative())
  357. {
  358. if (compareAbsolute (other) < 0)
  359. {
  360. BigInteger temp (other);
  361. swapWith (temp);
  362. operator-= (temp);
  363. negate();
  364. return *this;
  365. }
  366. }
  367. else
  368. {
  369. negate();
  370. operator+= (other);
  371. negate();
  372. return *this;
  373. }
  374. const size_t numInts = bitToIndex (highestBit) + 1;
  375. const size_t maxOtherInts = bitToIndex (other.highestBit) + 1;
  376. int64 amountToSubtract = 0;
  377. for (size_t i = 0; i <= numInts; ++i)
  378. {
  379. if (i <= maxOtherInts)
  380. amountToSubtract += (int64) other.values[i];
  381. if (values[i] >= amountToSubtract)
  382. {
  383. values[i] = (uint32) (values[i] - amountToSubtract);
  384. amountToSubtract = 0;
  385. }
  386. else
  387. {
  388. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  389. values[i] = (uint32) n;
  390. amountToSubtract = 1;
  391. }
  392. }
  393. return *this;
  394. }
  395. BigInteger& BigInteger::operator*= (const BigInteger& other)
  396. {
  397. BigInteger total;
  398. highestBit = getHighestBit();
  399. const bool wasNegative = isNegative();
  400. setNegative (false);
  401. for (int i = 0; i <= highestBit; ++i)
  402. {
  403. if (operator[](i))
  404. {
  405. BigInteger n (other);
  406. n.setNegative (false);
  407. n <<= i;
  408. total += n;
  409. }
  410. }
  411. total.setNegative (wasNegative ^ other.isNegative());
  412. swapWith (total);
  413. return *this;
  414. }
  415. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  416. {
  417. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  418. const int divHB = divisor.getHighestBit();
  419. const int ourHB = getHighestBit();
  420. if (divHB < 0 || ourHB < 0)
  421. {
  422. // division by zero
  423. remainder.clear();
  424. clear();
  425. }
  426. else
  427. {
  428. const bool wasNegative = isNegative();
  429. swapWith (remainder);
  430. remainder.setNegative (false);
  431. clear();
  432. BigInteger temp (divisor);
  433. temp.setNegative (false);
  434. int leftShift = ourHB - divHB;
  435. temp <<= leftShift;
  436. while (leftShift >= 0)
  437. {
  438. if (remainder.compareAbsolute (temp) >= 0)
  439. {
  440. remainder -= temp;
  441. setBit (leftShift);
  442. }
  443. if (--leftShift >= 0)
  444. temp >>= 1;
  445. }
  446. negative = wasNegative ^ divisor.isNegative();
  447. remainder.setNegative (wasNegative);
  448. }
  449. }
  450. BigInteger& BigInteger::operator/= (const BigInteger& other)
  451. {
  452. BigInteger remainder;
  453. divideBy (other, remainder);
  454. return *this;
  455. }
  456. BigInteger& BigInteger::operator|= (const BigInteger& other)
  457. {
  458. // this operation doesn't take into account negative values..
  459. jassert (isNegative() == other.isNegative());
  460. if (other.highestBit >= 0)
  461. {
  462. ensureSize (bitToIndex (other.highestBit));
  463. int n = (int) bitToIndex (other.highestBit) + 1;
  464. while (--n >= 0)
  465. values[n] |= other.values[n];
  466. if (other.highestBit > highestBit)
  467. highestBit = other.highestBit;
  468. highestBit = getHighestBit();
  469. }
  470. return *this;
  471. }
  472. BigInteger& BigInteger::operator&= (const BigInteger& other)
  473. {
  474. // this operation doesn't take into account negative values..
  475. jassert (isNegative() == other.isNegative());
  476. int n = (int) numValues;
  477. while (n > (int) other.numValues)
  478. values[--n] = 0;
  479. while (--n >= 0)
  480. values[n] &= other.values[n];
  481. if (other.highestBit < highestBit)
  482. highestBit = other.highestBit;
  483. highestBit = getHighestBit();
  484. return *this;
  485. }
  486. BigInteger& BigInteger::operator^= (const BigInteger& other)
  487. {
  488. // this operation will only work with the absolute values
  489. jassert (isNegative() == other.isNegative());
  490. if (other.highestBit >= 0)
  491. {
  492. ensureSize (bitToIndex (other.highestBit));
  493. int n = (int) bitToIndex (other.highestBit) + 1;
  494. while (--n >= 0)
  495. values[n] ^= other.values[n];
  496. if (other.highestBit > highestBit)
  497. highestBit = other.highestBit;
  498. highestBit = getHighestBit();
  499. }
  500. return *this;
  501. }
  502. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  503. {
  504. BigInteger remainder;
  505. divideBy (divisor, remainder);
  506. swapWith (remainder);
  507. return *this;
  508. }
  509. BigInteger& BigInteger::operator++() { return operator+= (1); }
  510. BigInteger& BigInteger::operator--() { return operator-= (1); }
  511. BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  512. BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  513. BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  514. BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  515. BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  516. BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  517. BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  518. BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  519. BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  520. BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  521. BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  522. BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  523. BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  524. BigInteger& BigInteger::operator<<= (const int numBits) { shiftBits (numBits, 0); return *this; }
  525. BigInteger& BigInteger::operator>>= (const int numBits) { shiftBits (-numBits, 0); return *this; }
  526. //==============================================================================
  527. int BigInteger::compare (const BigInteger& other) const noexcept
  528. {
  529. const bool isNeg = isNegative();
  530. if (isNeg == other.isNegative())
  531. {
  532. const int absComp = compareAbsolute (other);
  533. return isNeg ? -absComp : absComp;
  534. }
  535. return isNeg ? -1 : 1;
  536. }
  537. int BigInteger::compareAbsolute (const BigInteger& other) const noexcept
  538. {
  539. const int h1 = getHighestBit();
  540. const int h2 = other.getHighestBit();
  541. if (h1 > h2) return 1;
  542. if (h1 < h2) return -1;
  543. for (int i = (int) bitToIndex (h1) + 1; --i >= 0;)
  544. if (values[i] != other.values[i])
  545. return (values[i] > other.values[i]) ? 1 : -1;
  546. return 0;
  547. }
  548. bool BigInteger::operator== (const BigInteger& other) const noexcept { return compare (other) == 0; }
  549. bool BigInteger::operator!= (const BigInteger& other) const noexcept { return compare (other) != 0; }
  550. bool BigInteger::operator< (const BigInteger& other) const noexcept { return compare (other) < 0; }
  551. bool BigInteger::operator<= (const BigInteger& other) const noexcept { return compare (other) <= 0; }
  552. bool BigInteger::operator> (const BigInteger& other) const noexcept { return compare (other) > 0; }
  553. bool BigInteger::operator>= (const BigInteger& other) const noexcept { return compare (other) >= 0; }
  554. //==============================================================================
  555. void BigInteger::shiftLeft (int bits, const int startBit)
  556. {
  557. if (startBit > 0)
  558. {
  559. for (int i = highestBit + 1; --i >= startBit;)
  560. setBit (i + bits, operator[] (i));
  561. while (--bits >= 0)
  562. clearBit (bits + startBit);
  563. }
  564. else
  565. {
  566. ensureSize (bitToIndex (highestBit + bits) + 1);
  567. const size_t wordsToMove = bitToIndex (bits);
  568. size_t top = 1 + bitToIndex (highestBit);
  569. highestBit += bits;
  570. if (wordsToMove > 0)
  571. {
  572. for (int i = (int) top; --i >= 0;)
  573. values [(size_t) i + wordsToMove] = values [i];
  574. for (size_t j = 0; j < wordsToMove; ++j)
  575. values [j] = 0;
  576. bits &= 31;
  577. }
  578. if (bits != 0)
  579. {
  580. const int invBits = 32 - bits;
  581. for (size_t i = top + 1 + wordsToMove; --i > wordsToMove;)
  582. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  583. values [wordsToMove] = values [wordsToMove] << bits;
  584. }
  585. highestBit = getHighestBit();
  586. }
  587. }
  588. void BigInteger::shiftRight (int bits, const int startBit)
  589. {
  590. if (startBit > 0)
  591. {
  592. for (int i = startBit; i <= highestBit; ++i)
  593. setBit (i, operator[] (i + bits));
  594. highestBit = getHighestBit();
  595. }
  596. else
  597. {
  598. if (bits > highestBit)
  599. {
  600. clear();
  601. }
  602. else
  603. {
  604. const size_t wordsToMove = bitToIndex (bits);
  605. size_t top = 1 + bitToIndex (highestBit) - wordsToMove;
  606. highestBit -= bits;
  607. if (wordsToMove > 0)
  608. {
  609. size_t i;
  610. for (i = 0; i < top; ++i)
  611. values [i] = values [i + wordsToMove];
  612. for (i = 0; i < wordsToMove; ++i)
  613. values [top + i] = 0;
  614. bits &= 31;
  615. }
  616. if (bits != 0)
  617. {
  618. const int invBits = 32 - bits;
  619. --top;
  620. for (size_t i = 0; i < top; ++i)
  621. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  622. values[top] = (values[top] >> bits);
  623. }
  624. highestBit = getHighestBit();
  625. }
  626. }
  627. }
  628. void BigInteger::shiftBits (int bits, const int startBit)
  629. {
  630. if (highestBit >= 0)
  631. {
  632. if (bits < 0)
  633. shiftRight (-bits, startBit);
  634. else if (bits > 0)
  635. shiftLeft (bits, startBit);
  636. }
  637. }
  638. //==============================================================================
  639. static BigInteger simpleGCD (BigInteger* m, BigInteger* n)
  640. {
  641. while (! m->isZero())
  642. {
  643. if (n->compareAbsolute (*m) > 0)
  644. std::swap (m, n);
  645. *m -= *n;
  646. }
  647. return *n;
  648. }
  649. BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  650. {
  651. BigInteger m (*this);
  652. while (! n.isZero())
  653. {
  654. if (std::abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  655. return simpleGCD (&m, &n);
  656. BigInteger temp2;
  657. m.divideBy (n, temp2);
  658. m.swapWith (n);
  659. n.swapWith (temp2);
  660. }
  661. return m;
  662. }
  663. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  664. {
  665. BigInteger exp (exponent);
  666. exp %= modulus;
  667. BigInteger value (1);
  668. swapWith (value);
  669. value %= modulus;
  670. while (! exp.isZero())
  671. {
  672. if (exp [0])
  673. {
  674. operator*= (value);
  675. operator%= (modulus);
  676. }
  677. value *= value;
  678. value %= modulus;
  679. exp >>= 1;
  680. }
  681. }
  682. void BigInteger::inverseModulo (const BigInteger& modulus)
  683. {
  684. if (modulus.isOne() || modulus.isNegative())
  685. {
  686. clear();
  687. return;
  688. }
  689. if (isNegative() || compareAbsolute (modulus) >= 0)
  690. operator%= (modulus);
  691. if (isOne())
  692. return;
  693. if (findGreatestCommonDivisor (modulus) != 1)
  694. {
  695. clear(); // not invertible!
  696. return;
  697. }
  698. BigInteger a1 (modulus), a2 (*this);
  699. BigInteger b1 (modulus), b2 (1);
  700. while (! a2.isOne())
  701. {
  702. BigInteger temp1, multiplier (a1);
  703. multiplier.divideBy (a2, temp1);
  704. temp1 = a2;
  705. temp1 *= multiplier;
  706. BigInteger temp2 (a1);
  707. temp2 -= temp1;
  708. a1 = a2;
  709. a2 = temp2;
  710. temp1 = b2;
  711. temp1 *= multiplier;
  712. temp2 = b1;
  713. temp2 -= temp1;
  714. b1 = b2;
  715. b2 = temp2;
  716. }
  717. while (b2.isNegative())
  718. b2 += modulus;
  719. b2 %= modulus;
  720. swapWith (b2);
  721. }
  722. //==============================================================================
  723. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  724. {
  725. return stream << value.toString (10);
  726. }
  727. String BigInteger::toString (const int base, const int minimumNumCharacters) const
  728. {
  729. String s;
  730. BigInteger v (*this);
  731. if (base == 2 || base == 8 || base == 16)
  732. {
  733. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  734. static const char hexDigits[] = "0123456789abcdef";
  735. for (;;)
  736. {
  737. const uint32 remainder = v.getBitRangeAsInt (0, bits);
  738. v >>= bits;
  739. if (remainder == 0 && v.isZero())
  740. break;
  741. s = String::charToString ((juce_wchar) (uint8) hexDigits [remainder]) + s;
  742. }
  743. }
  744. else if (base == 10)
  745. {
  746. const BigInteger ten (10);
  747. BigInteger remainder;
  748. for (;;)
  749. {
  750. v.divideBy (ten, remainder);
  751. if (remainder.isZero() && v.isZero())
  752. break;
  753. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  754. }
  755. }
  756. else
  757. {
  758. jassertfalse; // can't do the specified base!
  759. return String();
  760. }
  761. s = s.paddedLeft ('0', minimumNumCharacters);
  762. return isNegative() ? "-" + s : s;
  763. }
  764. void BigInteger::parseString (StringRef text, const int base)
  765. {
  766. clear();
  767. String::CharPointerType t (text.text.findEndOfWhitespace());
  768. setNegative (*t == (juce_wchar) '-');
  769. if (base == 2 || base == 8 || base == 16)
  770. {
  771. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  772. for (;;)
  773. {
  774. const juce_wchar c = t.getAndAdvance();
  775. const int digit = CharacterFunctions::getHexDigitValue (c);
  776. if (((uint32) digit) < (uint32) base)
  777. {
  778. operator<<= (bits);
  779. operator+= (digit);
  780. }
  781. else if (c == 0)
  782. {
  783. break;
  784. }
  785. }
  786. }
  787. else if (base == 10)
  788. {
  789. const BigInteger ten ((uint32) 10);
  790. for (;;)
  791. {
  792. const juce_wchar c = t.getAndAdvance();
  793. if (c >= '0' && c <= '9')
  794. {
  795. operator*= (ten);
  796. operator+= ((int) (c - '0'));
  797. }
  798. else if (c == 0)
  799. {
  800. break;
  801. }
  802. }
  803. }
  804. }
  805. MemoryBlock BigInteger::toMemoryBlock() const
  806. {
  807. const int numBytes = (getHighestBit() + 8) >> 3;
  808. MemoryBlock mb ((size_t) numBytes);
  809. for (int i = 0; i < numBytes; ++i)
  810. mb[i] = (char) ((values[i / 4] >> ((i & 3) * 8)) & 0xff);
  811. return mb;
  812. }
  813. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  814. {
  815. const size_t numBytes = data.getSize();
  816. numValues = 1 + (numBytes / sizeof (uint32));
  817. values.malloc (numValues + 1);
  818. for (int i = 0; i < (int) numValues - 1; ++i)
  819. values[i] = (uint32) ByteOrder::littleEndianInt (addBytesToPointer (data.getData(), sizeof (uint32) * (size_t) i));
  820. values[numValues - 1] = 0;
  821. values[numValues] = 0;
  822. for (int i = (int) (numBytes & ~3u); i < (int) numBytes; ++i)
  823. this->setBitRangeAsInt (i << 3, 8, (uint32) data [i]);
  824. highestBit = (int) numBytes * 8;
  825. highestBit = getHighestBit();
  826. }
  827. //==============================================================================
  828. //==============================================================================
  829. #if JUCE_UNIT_TESTS
  830. class BigIntegerTests : public UnitTest
  831. {
  832. public:
  833. BigIntegerTests() : UnitTest ("BigInteger") {}
  834. static BigInteger getBigRandom (Random& r)
  835. {
  836. BigInteger b;
  837. while (b < 2)
  838. r.fillBitsRandomly (b, 0, r.nextInt (150) + 1);
  839. return b;
  840. }
  841. void runTest() override
  842. {
  843. beginTest ("BigInteger");
  844. Random r = getRandom();
  845. expect (BigInteger().isZero());
  846. expect (BigInteger(1).isOne());
  847. for (int j = 10000; --j >= 0;)
  848. {
  849. BigInteger b1 (getBigRandom(r)),
  850. b2 (getBigRandom(r));
  851. BigInteger b3 = b1 + b2;
  852. expect (b3 > b1 && b3 > b2);
  853. expect (b3 - b1 == b2);
  854. expect (b3 - b2 == b1);
  855. BigInteger b4 = b1 * b2;
  856. expect (b4 > b1 && b4 > b2);
  857. expect (b4 / b1 == b2);
  858. expect (b4 / b2 == b1);
  859. // TODO: should add tests for other ops (although they also get pretty well tested in the RSA unit test)
  860. BigInteger b5;
  861. b5.loadFromMemoryBlock (b3.toMemoryBlock());
  862. expect (b3 == b5);
  863. }
  864. }
  865. };
  866. static BigIntegerTests bigIntegerTests;
  867. #endif