juce_BigInteger.cpp 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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) 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_USE_INTRINSICS && ! defined (__INTEL_COMPILER)
  258. #pragma intrinsic (_BitScanReverse)
  259. #endif
  260. namespace BitFunctions
  261. {
  262. inline int countBitsInInt32 (uint32 n) noexcept
  263. {
  264. n -= ((n >> 1) & 0x55555555);
  265. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  266. n = (((n >> 4) + n) & 0x0f0f0f0f);
  267. n += (n >> 8);
  268. n += (n >> 16);
  269. return (int) (n & 0x3f);
  270. }
  271. inline int highestBitInInt (uint32 n) noexcept
  272. {
  273. jassert (n != 0); // (the built-in functions may not work for n = 0)
  274. #if JUCE_GCC
  275. return 31 - __builtin_clz (n);
  276. #elif JUCE_USE_INTRINSICS
  277. unsigned long highest;
  278. _BitScanReverse (&highest, n);
  279. return (int) highest;
  280. #else
  281. n |= (n >> 1);
  282. n |= (n >> 2);
  283. n |= (n >> 4);
  284. n |= (n >> 8);
  285. n |= (n >> 16);
  286. return countBitsInInt32 (n >> 1);
  287. #endif
  288. }
  289. }
  290. int BigInteger::countNumberOfSetBits() const noexcept
  291. {
  292. int total = 0;
  293. for (int i = (int) bitToIndex (highestBit) + 1; --i >= 0;)
  294. total += BitFunctions::countBitsInInt32 (values[i]);
  295. return total;
  296. }
  297. int BigInteger::getHighestBit() const noexcept
  298. {
  299. for (int i = (int) bitToIndex (highestBit + 1); i >= 0; --i)
  300. {
  301. const uint32 n = values[i];
  302. if (n != 0)
  303. return BitFunctions::highestBitInInt (n) + (i << 5);
  304. }
  305. return -1;
  306. }
  307. int BigInteger::findNextSetBit (int i) const noexcept
  308. {
  309. for (; i <= highestBit; ++i)
  310. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  311. return i;
  312. return -1;
  313. }
  314. int BigInteger::findNextClearBit (int i) const noexcept
  315. {
  316. for (; i <= highestBit; ++i)
  317. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  318. break;
  319. return i;
  320. }
  321. //==============================================================================
  322. BigInteger& BigInteger::operator+= (const BigInteger& other)
  323. {
  324. if (other.isNegative())
  325. return operator-= (-other);
  326. if (isNegative())
  327. {
  328. if (compareAbsolute (other) < 0)
  329. {
  330. BigInteger temp (*this);
  331. temp.negate();
  332. *this = other;
  333. operator-= (temp);
  334. }
  335. else
  336. {
  337. negate();
  338. operator-= (other);
  339. negate();
  340. }
  341. }
  342. else
  343. {
  344. if (other.highestBit > highestBit)
  345. highestBit = other.highestBit;
  346. ++highestBit;
  347. const size_t numInts = bitToIndex (highestBit) + 1;
  348. ensureSize (numInts);
  349. int64 remainder = 0;
  350. for (size_t i = 0; i <= numInts; ++i)
  351. {
  352. if (i < numValues)
  353. remainder += values[i];
  354. if (i < other.numValues)
  355. remainder += other.values[i];
  356. values[i] = (uint32) remainder;
  357. remainder >>= 32;
  358. }
  359. jassert (remainder == 0);
  360. highestBit = getHighestBit();
  361. }
  362. return *this;
  363. }
  364. BigInteger& BigInteger::operator-= (const BigInteger& other)
  365. {
  366. if (other.isNegative())
  367. return operator+= (-other);
  368. if (! isNegative())
  369. {
  370. if (compareAbsolute (other) < 0)
  371. {
  372. BigInteger temp (other);
  373. swapWith (temp);
  374. operator-= (temp);
  375. negate();
  376. return *this;
  377. }
  378. }
  379. else
  380. {
  381. negate();
  382. operator+= (other);
  383. negate();
  384. return *this;
  385. }
  386. const size_t numInts = bitToIndex (highestBit) + 1;
  387. const size_t maxOtherInts = bitToIndex (other.highestBit) + 1;
  388. int64 amountToSubtract = 0;
  389. for (size_t i = 0; i <= numInts; ++i)
  390. {
  391. if (i <= maxOtherInts)
  392. amountToSubtract += (int64) other.values[i];
  393. if (values[i] >= amountToSubtract)
  394. {
  395. values[i] = (uint32) (values[i] - amountToSubtract);
  396. amountToSubtract = 0;
  397. }
  398. else
  399. {
  400. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  401. values[i] = (uint32) n;
  402. amountToSubtract = 1;
  403. }
  404. }
  405. return *this;
  406. }
  407. BigInteger& BigInteger::operator*= (const BigInteger& other)
  408. {
  409. BigInteger total;
  410. highestBit = getHighestBit();
  411. const bool wasNegative = isNegative();
  412. setNegative (false);
  413. for (int i = 0; i <= highestBit; ++i)
  414. {
  415. if (operator[](i))
  416. {
  417. BigInteger n (other);
  418. n.setNegative (false);
  419. n <<= i;
  420. total += n;
  421. }
  422. }
  423. total.setNegative (wasNegative ^ other.isNegative());
  424. swapWith (total);
  425. return *this;
  426. }
  427. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  428. {
  429. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  430. const int divHB = divisor.getHighestBit();
  431. const int ourHB = getHighestBit();
  432. if (divHB < 0 || ourHB < 0)
  433. {
  434. // division by zero
  435. remainder.clear();
  436. clear();
  437. }
  438. else
  439. {
  440. const bool wasNegative = isNegative();
  441. swapWith (remainder);
  442. remainder.setNegative (false);
  443. clear();
  444. BigInteger temp (divisor);
  445. temp.setNegative (false);
  446. int leftShift = ourHB - divHB;
  447. temp <<= leftShift;
  448. while (leftShift >= 0)
  449. {
  450. if (remainder.compareAbsolute (temp) >= 0)
  451. {
  452. remainder -= temp;
  453. setBit (leftShift);
  454. }
  455. if (--leftShift >= 0)
  456. temp >>= 1;
  457. }
  458. negative = wasNegative ^ divisor.isNegative();
  459. remainder.setNegative (wasNegative);
  460. }
  461. }
  462. BigInteger& BigInteger::operator/= (const BigInteger& other)
  463. {
  464. BigInteger remainder;
  465. divideBy (other, remainder);
  466. return *this;
  467. }
  468. BigInteger& BigInteger::operator|= (const BigInteger& other)
  469. {
  470. // this operation doesn't take into account negative values..
  471. jassert (isNegative() == other.isNegative());
  472. if (other.highestBit >= 0)
  473. {
  474. ensureSize (bitToIndex (other.highestBit));
  475. int n = (int) bitToIndex (other.highestBit) + 1;
  476. while (--n >= 0)
  477. values[n] |= other.values[n];
  478. if (other.highestBit > highestBit)
  479. highestBit = other.highestBit;
  480. highestBit = getHighestBit();
  481. }
  482. return *this;
  483. }
  484. BigInteger& BigInteger::operator&= (const BigInteger& other)
  485. {
  486. // this operation doesn't take into account negative values..
  487. jassert (isNegative() == other.isNegative());
  488. int n = (int) numValues;
  489. while (n > (int) other.numValues)
  490. values[--n] = 0;
  491. while (--n >= 0)
  492. values[n] &= other.values[n];
  493. if (other.highestBit < highestBit)
  494. highestBit = other.highestBit;
  495. highestBit = getHighestBit();
  496. return *this;
  497. }
  498. BigInteger& BigInteger::operator^= (const BigInteger& other)
  499. {
  500. // this operation will only work with the absolute values
  501. jassert (isNegative() == other.isNegative());
  502. if (other.highestBit >= 0)
  503. {
  504. ensureSize (bitToIndex (other.highestBit));
  505. int n = (int) bitToIndex (other.highestBit) + 1;
  506. while (--n >= 0)
  507. values[n] ^= other.values[n];
  508. if (other.highestBit > highestBit)
  509. highestBit = other.highestBit;
  510. highestBit = getHighestBit();
  511. }
  512. return *this;
  513. }
  514. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  515. {
  516. BigInteger remainder;
  517. divideBy (divisor, remainder);
  518. swapWith (remainder);
  519. return *this;
  520. }
  521. BigInteger& BigInteger::operator++() { return operator+= (1); }
  522. BigInteger& BigInteger::operator--() { return operator-= (1); }
  523. BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  524. BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  525. BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  526. BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  527. BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  528. BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  529. BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  530. BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  531. BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  532. BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  533. BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  534. BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  535. BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  536. BigInteger& BigInteger::operator<<= (const int numBits) { shiftBits (numBits, 0); return *this; }
  537. BigInteger& BigInteger::operator>>= (const int numBits) { shiftBits (-numBits, 0); return *this; }
  538. //==============================================================================
  539. int BigInteger::compare (const BigInteger& other) const noexcept
  540. {
  541. if (isNegative() == other.isNegative())
  542. {
  543. const int absComp = compareAbsolute (other);
  544. return isNegative() ? -absComp : absComp;
  545. }
  546. else
  547. {
  548. return isNegative() ? -1 : 1;
  549. }
  550. }
  551. int BigInteger::compareAbsolute (const BigInteger& other) const noexcept
  552. {
  553. const int h1 = getHighestBit();
  554. const int h2 = other.getHighestBit();
  555. if (h1 > h2)
  556. return 1;
  557. else if (h1 < h2)
  558. return -1;
  559. for (int i = (int) bitToIndex (h1) + 1; --i >= 0;)
  560. if (values[i] != other.values[i])
  561. return (values[i] > other.values[i]) ? 1 : -1;
  562. return 0;
  563. }
  564. bool BigInteger::operator== (const BigInteger& other) const noexcept { return compare (other) == 0; }
  565. bool BigInteger::operator!= (const BigInteger& other) const noexcept { return compare (other) != 0; }
  566. bool BigInteger::operator< (const BigInteger& other) const noexcept { return compare (other) < 0; }
  567. bool BigInteger::operator<= (const BigInteger& other) const noexcept { return compare (other) <= 0; }
  568. bool BigInteger::operator> (const BigInteger& other) const noexcept { return compare (other) > 0; }
  569. bool BigInteger::operator>= (const BigInteger& other) const noexcept { return compare (other) >= 0; }
  570. //==============================================================================
  571. void BigInteger::shiftLeft (int bits, const int startBit)
  572. {
  573. if (startBit > 0)
  574. {
  575. for (int i = highestBit + 1; --i >= startBit;)
  576. setBit (i + bits, operator[] (i));
  577. while (--bits >= 0)
  578. clearBit (bits + startBit);
  579. }
  580. else
  581. {
  582. ensureSize (bitToIndex (highestBit + bits) + 1);
  583. const size_t wordsToMove = bitToIndex (bits);
  584. size_t top = 1 + bitToIndex (highestBit);
  585. highestBit += bits;
  586. if (wordsToMove > 0)
  587. {
  588. for (int i = (int) top; --i >= 0;)
  589. values [(size_t) i + wordsToMove] = values [i];
  590. for (size_t j = 0; j < wordsToMove; ++j)
  591. values [j] = 0;
  592. bits &= 31;
  593. }
  594. if (bits != 0)
  595. {
  596. const int invBits = 32 - bits;
  597. for (size_t i = top + 1 + wordsToMove; --i > wordsToMove;)
  598. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  599. values [wordsToMove] = values [wordsToMove] << bits;
  600. }
  601. highestBit = getHighestBit();
  602. }
  603. }
  604. void BigInteger::shiftRight (int bits, const int startBit)
  605. {
  606. if (startBit > 0)
  607. {
  608. for (int i = startBit; i <= highestBit; ++i)
  609. setBit (i, operator[] (i + bits));
  610. highestBit = getHighestBit();
  611. }
  612. else
  613. {
  614. if (bits > highestBit)
  615. {
  616. clear();
  617. }
  618. else
  619. {
  620. const size_t wordsToMove = bitToIndex (bits);
  621. size_t top = 1 + bitToIndex (highestBit) - wordsToMove;
  622. highestBit -= bits;
  623. if (wordsToMove > 0)
  624. {
  625. size_t i;
  626. for (i = 0; i < top; ++i)
  627. values [i] = values [i + wordsToMove];
  628. for (i = 0; i < wordsToMove; ++i)
  629. values [top + i] = 0;
  630. bits &= 31;
  631. }
  632. if (bits != 0)
  633. {
  634. const int invBits = 32 - bits;
  635. --top;
  636. for (size_t i = 0; i < top; ++i)
  637. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  638. values[top] = (values[top] >> bits);
  639. }
  640. highestBit = getHighestBit();
  641. }
  642. }
  643. }
  644. void BigInteger::shiftBits (int bits, const int startBit)
  645. {
  646. if (highestBit >= 0)
  647. {
  648. if (bits < 0)
  649. shiftRight (-bits, startBit);
  650. else if (bits > 0)
  651. shiftLeft (bits, startBit);
  652. }
  653. }
  654. //==============================================================================
  655. static BigInteger simpleGCD (BigInteger* m, BigInteger* n)
  656. {
  657. while (! m->isZero())
  658. {
  659. if (n->compareAbsolute (*m) > 0)
  660. std::swap (m, n);
  661. *m -= *n;
  662. }
  663. return *n;
  664. }
  665. BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  666. {
  667. BigInteger m (*this);
  668. while (! n.isZero())
  669. {
  670. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  671. return simpleGCD (&m, &n);
  672. BigInteger temp2;
  673. m.divideBy (n, temp2);
  674. m.swapWith (n);
  675. n.swapWith (temp2);
  676. }
  677. return m;
  678. }
  679. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  680. {
  681. BigInteger exp (exponent);
  682. exp %= modulus;
  683. BigInteger value (1);
  684. swapWith (value);
  685. value %= modulus;
  686. while (! exp.isZero())
  687. {
  688. if (exp [0])
  689. {
  690. operator*= (value);
  691. operator%= (modulus);
  692. }
  693. value *= value;
  694. value %= modulus;
  695. exp >>= 1;
  696. }
  697. }
  698. void BigInteger::inverseModulo (const BigInteger& modulus)
  699. {
  700. if (modulus.isOne() || modulus.isNegative())
  701. {
  702. clear();
  703. return;
  704. }
  705. if (isNegative() || compareAbsolute (modulus) >= 0)
  706. operator%= (modulus);
  707. if (isOne())
  708. return;
  709. if (! (*this)[0])
  710. {
  711. // not invertible
  712. clear();
  713. return;
  714. }
  715. BigInteger a1 (modulus);
  716. BigInteger a2 (*this);
  717. BigInteger b1 (modulus);
  718. BigInteger b2 (1);
  719. while (! a2.isOne())
  720. {
  721. BigInteger temp1, multiplier (a1);
  722. multiplier.divideBy (a2, temp1);
  723. temp1 = a2;
  724. temp1 *= multiplier;
  725. BigInteger temp2 (a1);
  726. temp2 -= temp1;
  727. a1 = a2;
  728. a2 = temp2;
  729. temp1 = b2;
  730. temp1 *= multiplier;
  731. temp2 = b1;
  732. temp2 -= temp1;
  733. b1 = b2;
  734. b2 = temp2;
  735. }
  736. while (b2.isNegative())
  737. b2 += modulus;
  738. b2 %= modulus;
  739. swapWith (b2);
  740. }
  741. //==============================================================================
  742. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  743. {
  744. return stream << value.toString (10);
  745. }
  746. String BigInteger::toString (const int base, const int minimumNumCharacters) const
  747. {
  748. String s;
  749. BigInteger v (*this);
  750. if (base == 2 || base == 8 || base == 16)
  751. {
  752. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  753. static const char hexDigits[] = "0123456789abcdef";
  754. for (;;)
  755. {
  756. const uint32 remainder = v.getBitRangeAsInt (0, bits);
  757. v >>= bits;
  758. if (remainder == 0 && v.isZero())
  759. break;
  760. s = String::charToString ((juce_wchar) (uint8) hexDigits [remainder]) + s;
  761. }
  762. }
  763. else if (base == 10)
  764. {
  765. const BigInteger ten (10);
  766. BigInteger remainder;
  767. for (;;)
  768. {
  769. v.divideBy (ten, remainder);
  770. if (remainder.isZero() && v.isZero())
  771. break;
  772. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  773. }
  774. }
  775. else
  776. {
  777. jassertfalse; // can't do the specified base!
  778. return String();
  779. }
  780. s = s.paddedLeft ('0', minimumNumCharacters);
  781. return isNegative() ? "-" + s : s;
  782. }
  783. void BigInteger::parseString (StringRef text, const int base)
  784. {
  785. clear();
  786. String::CharPointerType t (text.text.findEndOfWhitespace());
  787. setNegative (*t == (juce_wchar) '-');
  788. if (base == 2 || base == 8 || base == 16)
  789. {
  790. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  791. for (;;)
  792. {
  793. const juce_wchar c = t.getAndAdvance();
  794. const int digit = CharacterFunctions::getHexDigitValue (c);
  795. if (((uint32) digit) < (uint32) base)
  796. {
  797. operator<<= (bits);
  798. operator+= (digit);
  799. }
  800. else if (c == 0)
  801. {
  802. break;
  803. }
  804. }
  805. }
  806. else if (base == 10)
  807. {
  808. const BigInteger ten ((uint32) 10);
  809. for (;;)
  810. {
  811. const juce_wchar c = t.getAndAdvance();
  812. if (c >= '0' && c <= '9')
  813. {
  814. operator*= (ten);
  815. operator+= ((int) (c - '0'));
  816. }
  817. else if (c == 0)
  818. {
  819. break;
  820. }
  821. }
  822. }
  823. }
  824. MemoryBlock BigInteger::toMemoryBlock() const
  825. {
  826. const int numBytes = (getHighestBit() + 8) >> 3;
  827. MemoryBlock mb ((size_t) numBytes);
  828. for (int i = 0; i < numBytes; ++i)
  829. mb[i] = (char) getBitRangeAsInt (i << 3, 8);
  830. return mb;
  831. }
  832. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  833. {
  834. clear();
  835. for (int i = (int) data.getSize(); --i >= 0;)
  836. this->setBitRangeAsInt (i << 3, 8, (uint32) data [i]);
  837. }