MutableBigInteger.java 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327
  1. package client;
  2. /*
  3. * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  4. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  5. *
  6. *
  7. *
  8. *
  9. *
  10. *
  11. *
  12. *
  13. *
  14. *
  15. *
  16. *
  17. *
  18. *
  19. *
  20. *
  21. *
  22. *
  23. *
  24. *
  25. */
  26. /**
  27. * A class used to represent multiprecision integers that makes efficient
  28. * use of allocated space by allowing a number to occupy only part of
  29. * an array so that the arrays do not have to be reallocated as often.
  30. * When performing an operation with many iterations the array used to
  31. * hold a number is only reallocated when necessary and does not have to
  32. * be the same size as the number it represents. A mutable number allows
  33. * calculations to occur on the same number without having to create
  34. * a new number for every step of the calculation as occurs with
  35. * BigIntegers.
  36. *
  37. * @see BigInteger
  38. * @author Michael McCloskey
  39. * @author Timothy Buktu
  40. * @since 1.3
  41. */
  42. import java.util.Arrays;
  43. class MutableBigInteger {
  44. final static long LONG_MASK = 0xffffffffL;
  45. final static long INFLATED = Long.MIN_VALUE;
  46. /**
  47. * Holds the magnitude of this MutableBigInteger in big endian order.
  48. * The magnitude may start at an offset into the value array, and it may
  49. * end before the length of the value array.
  50. */
  51. int[] value;
  52. /**
  53. * The number of ints of the value array that are currently used
  54. * to hold the magnitude of this MutableBigInteger. The magnitude starts
  55. * at an offset and offset + intLen may be less than value.length.
  56. */
  57. int intLen;
  58. /**
  59. * The offset into the value array where the magnitude of this
  60. * MutableBigInteger begins.
  61. */
  62. int offset = 0;
  63. // Constants
  64. /**
  65. * MutableBigInteger with one element value array with the value 1. Used by
  66. * BigDecimal divideAndRound to increment the quotient. Use this constant
  67. * only when the method is not going to modify this object.
  68. */
  69. static final MutableBigInteger ONE = new MutableBigInteger(1);
  70. /**
  71. * The minimum {@code intLen} for cancelling powers of two before
  72. * dividing.
  73. * If the number of ints is less than this threshold,
  74. * {@code divideKnuth} does not eliminate common powers of two from
  75. * the dividend and divisor.
  76. */
  77. static final int KNUTH_POW2_THRESH_LEN = 6;
  78. /**
  79. * The minimum number of trailing zero ints for cancelling powers of two
  80. * before dividing.
  81. * If the dividend and divisor don't share at least this many zero ints
  82. * at the end, {@code divideKnuth} does not eliminate common powers
  83. * of two from the dividend and divisor.
  84. */
  85. static final int KNUTH_POW2_THRESH_ZEROS = 3;
  86. // Constructors
  87. /**
  88. * The default constructor. An empty MutableBigInteger is created with
  89. * a one word capacity.
  90. */
  91. MutableBigInteger() {
  92. value = new int[1];
  93. intLen = 0;
  94. }
  95. /**
  96. * Construct a new MutableBigInteger with a magnitude specified by
  97. * the int val.
  98. */
  99. MutableBigInteger(int val) {
  100. value = new int[1];
  101. intLen = 1;
  102. value[0] = val;
  103. }
  104. /**
  105. * Construct a new MutableBigInteger with the specified value array
  106. * up to the length of the array supplied.
  107. */
  108. MutableBigInteger(int[] val) {
  109. value = val;
  110. intLen = val.length;
  111. }
  112. /**
  113. * Construct a new MutableBigInteger with a magnitude equal to the
  114. * specified BigInteger.
  115. */
  116. MutableBigInteger(BigInteger b) {
  117. intLen = b.mag.length;
  118. value = Arrays.copyOf(b.mag, intLen);
  119. }
  120. /**
  121. * Construct a new MutableBigInteger with a magnitude equal to the
  122. * specified MutableBigInteger.
  123. */
  124. MutableBigInteger(MutableBigInteger val) {
  125. intLen = val.intLen;
  126. value = Arrays.copyOfRange(val.value, val.offset, val.offset + intLen);
  127. }
  128. /**
  129. * Makes this number an {@code n}-int number all of whose bits are ones.
  130. * Used by Burnikel-Ziegler division.
  131. * @param n number of ints in the {@code value} array
  132. * @return a number equal to {@code ((1<<(32*n)))-1}
  133. */
  134. private void ones(int n) {
  135. if (n > value.length)
  136. value = new int[n];
  137. Arrays.fill(value, -1);
  138. offset = 0;
  139. intLen = n;
  140. }
  141. /**
  142. * Internal helper method to return the magnitude array. The caller is not
  143. * supposed to modify the returned array.
  144. */
  145. private int[] getMagnitudeArray() {
  146. if (offset > 0 || value.length != intLen)
  147. return Arrays.copyOfRange(value, offset, offset + intLen);
  148. return value;
  149. }
  150. /**
  151. * Convert this MutableBigInteger to a long value. The caller has to make
  152. * sure this MutableBigInteger can be fit into long.
  153. */
  154. private long toLong() {
  155. assert (intLen <= 2) : "this MutableBigInteger exceeds the range of long";
  156. if (intLen == 0)
  157. return 0;
  158. long d = value[offset] & LONG_MASK;
  159. return (intLen == 2) ? d << 32 | (value[offset + 1] & LONG_MASK) : d;
  160. }
  161. /**
  162. * Convert this MutableBigInteger to a BigInteger object.
  163. */
  164. BigInteger toBigInteger(int sign) {
  165. if (intLen == 0 || sign == 0)
  166. return BigInteger.ZERO;
  167. return new BigInteger(getMagnitudeArray(), sign);
  168. }
  169. /**
  170. * Converts this number to a nonnegative {@code BigInteger}.
  171. */
  172. BigInteger toBigInteger() {
  173. normalize();
  174. return toBigInteger(isZero() ? 0 : 1);
  175. }
  176. /**
  177. * Convert this MutableBigInteger to BigDecimal object with the specified sign
  178. * and scale.
  179. */
  180. /**
  181. * This is for internal use in converting from a MutableBigInteger
  182. * object into a long value given a specified sign.
  183. * returns INFLATED if value is not fit into long
  184. */
  185. long toCompactValue(int sign) {
  186. if (intLen == 0 || sign == 0)
  187. return 0L;
  188. int[] mag = getMagnitudeArray();
  189. int len = mag.length;
  190. int d = mag[0];
  191. // If this MutableBigInteger can not be fitted into long, we need to
  192. // make a BigInteger object for the resultant BigDecimal object.
  193. if (len > 2 || (d < 0 && len == 2))
  194. return INFLATED;
  195. long v = (len == 2) ?
  196. ((mag[1] & LONG_MASK) | (d & LONG_MASK) << 32) :
  197. d & LONG_MASK;
  198. return sign == -1 ? -v : v;
  199. }
  200. /**
  201. * Clear out a MutableBigInteger for reuse.
  202. */
  203. void clear() {
  204. offset = intLen = 0;
  205. for (int index=0, n=value.length; index < n; index++)
  206. value[index] = 0;
  207. }
  208. /**
  209. * Set a MutableBigInteger to zero, removing its offset.
  210. */
  211. void reset() {
  212. offset = intLen = 0;
  213. }
  214. /**
  215. * Compare the magnitude of two MutableBigIntegers. Returns -1, 0 or 1
  216. * as this MutableBigInteger is numerically less than, equal to, or
  217. * greater than <tt>b</tt>.
  218. */
  219. final int compare(MutableBigInteger b) {
  220. int blen = b.intLen;
  221. if (intLen < blen)
  222. return -1;
  223. if (intLen > blen)
  224. return 1;
  225. // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
  226. // comparison.
  227. int[] bval = b.value;
  228. for (int i = offset, j = b.offset; i < intLen + offset; i++, j++) {
  229. int b1 = value[i] + 0x80000000;
  230. int b2 = bval[j] + 0x80000000;
  231. if (b1 < b2)
  232. return -1;
  233. if (b1 > b2)
  234. return 1;
  235. }
  236. return 0;
  237. }
  238. /**
  239. * Returns a value equal to what {@code b.leftShift(32*ints); return compare(b);}
  240. * would return, but doesn't change the value of {@code b}.
  241. */
  242. private int compareShifted(MutableBigInteger b, int ints) {
  243. int blen = b.intLen;
  244. int alen = intLen - ints;
  245. if (alen < blen)
  246. return -1;
  247. if (alen > blen)
  248. return 1;
  249. // Add Integer.MIN_VALUE to make the comparison act as unsigned integer
  250. // comparison.
  251. int[] bval = b.value;
  252. for (int i = offset, j = b.offset; i < alen + offset; i++, j++) {
  253. int b1 = value[i] + 0x80000000;
  254. int b2 = bval[j] + 0x80000000;
  255. if (b1 < b2)
  256. return -1;
  257. if (b1 > b2)
  258. return 1;
  259. }
  260. return 0;
  261. }
  262. /**
  263. * Compare this against half of a MutableBigInteger object (Needed for
  264. * remainder tests).
  265. * Assumes no leading unnecessary zeros, which holds for results
  266. * from divide().
  267. */
  268. final int compareHalf(MutableBigInteger b) {
  269. int blen = b.intLen;
  270. int len = intLen;
  271. if (len <= 0)
  272. return blen <= 0 ? 0 : -1;
  273. if (len > blen)
  274. return 1;
  275. if (len < blen - 1)
  276. return -1;
  277. int[] bval = b.value;
  278. int bstart = 0;
  279. int carry = 0;
  280. // Only 2 cases left:len == blen or len == blen - 1
  281. if (len != blen) { // len == blen - 1
  282. if (bval[bstart] == 1) {
  283. ++bstart;
  284. carry = 0x80000000;
  285. } else
  286. return -1;
  287. }
  288. // compare values with right-shifted values of b,
  289. // carrying shifted-out bits across words
  290. int[] val = value;
  291. for (int i = offset, j = bstart; i < len + offset;) {
  292. int bv = bval[j++];
  293. long hb = ((bv >>> 1) + carry) & LONG_MASK;
  294. long v = val[i++] & LONG_MASK;
  295. if (v != hb)
  296. return v < hb ? -1 : 1;
  297. carry = (bv & 1) << 31; // carray will be either 0x80000000 or 0
  298. }
  299. return carry == 0 ? 0 : -1;
  300. }
  301. /**
  302. * Return the index of the lowest set bit in this MutableBigInteger. If the
  303. * magnitude of this MutableBigInteger is zero, -1 is returned.
  304. */
  305. private final int getLowestSetBit() {
  306. if (intLen == 0)
  307. return -1;
  308. int j, b;
  309. for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--)
  310. ;
  311. b = value[j+offset];
  312. if (b == 0)
  313. return -1;
  314. return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(b);
  315. }
  316. /**
  317. * Return the int in use in this MutableBigInteger at the specified
  318. * index. This method is not used because it is not inlined on all
  319. * platforms.
  320. */
  321. private final int getInt(int index) {
  322. return value[offset+index];
  323. }
  324. /**
  325. * Return a long which is equal to the unsigned value of the int in
  326. * use in this MutableBigInteger at the specified index. This method is
  327. * not used because it is not inlined on all platforms.
  328. */
  329. private final long getLong(int index) {
  330. return value[offset+index] & LONG_MASK;
  331. }
  332. /**
  333. * Ensure that the MutableBigInteger is in normal form, specifically
  334. * making sure that there are no leading zeros, and that if the
  335. * magnitude is zero, then intLen is zero.
  336. */
  337. final void normalize() {
  338. if (intLen == 0) {
  339. offset = 0;
  340. return;
  341. }
  342. int index = offset;
  343. if (value[index] != 0)
  344. return;
  345. int indexBound = index+intLen;
  346. do {
  347. index++;
  348. } while(index < indexBound && value[index] == 0);
  349. int numZeros = index - offset;
  350. intLen -= numZeros;
  351. offset = (intLen == 0 ? 0 : offset+numZeros);
  352. }
  353. /**
  354. * If this MutableBigInteger cannot hold len words, increase the size
  355. * of the value array to len words.
  356. */
  357. private final void ensureCapacity(int len) {
  358. if (value.length < len) {
  359. value = new int[len];
  360. offset = 0;
  361. intLen = len;
  362. }
  363. }
  364. /**
  365. * Convert this MutableBigInteger into an int array with no leading
  366. * zeros, of a length that is equal to this MutableBigInteger's intLen.
  367. */
  368. int[] toIntArray() {
  369. int[] result = new int[intLen];
  370. for(int i=0; i < intLen; i++)
  371. result[i] = value[offset+i];
  372. return result;
  373. }
  374. /**
  375. * Sets the int at index+offset in this MutableBigInteger to val.
  376. * This does not get inlined on all platforms so it is not used
  377. * as often as originally intended.
  378. */
  379. void setInt(int index, int val) {
  380. value[offset + index] = val;
  381. }
  382. /**
  383. * Sets this MutableBigInteger's value array to the specified array.
  384. * The intLen is set to the specified length.
  385. */
  386. void setValue(int[] val, int length) {
  387. value = val;
  388. intLen = length;
  389. offset = 0;
  390. }
  391. /**
  392. * Sets this MutableBigInteger's value array to a copy of the specified
  393. * array. The intLen is set to the length of the new array.
  394. */
  395. void copyValue(MutableBigInteger src) {
  396. int len = src.intLen;
  397. if (value.length < len)
  398. value = new int[len];
  399. System.arraycopy(src.value, src.offset, value, 0, len);
  400. intLen = len;
  401. offset = 0;
  402. }
  403. /**
  404. * Sets this MutableBigInteger's value array to a copy of the specified
  405. * array. The intLen is set to the length of the specified array.
  406. */
  407. void copyValue(int[] val) {
  408. int len = val.length;
  409. if (value.length < len)
  410. value = new int[len];
  411. System.arraycopy(val, 0, value, 0, len);
  412. intLen = len;
  413. offset = 0;
  414. }
  415. /**
  416. * Returns true iff this MutableBigInteger has a value of one.
  417. */
  418. boolean isOne() {
  419. return (intLen == 1) && (value[offset] == 1);
  420. }
  421. /**
  422. * Returns true iff this MutableBigInteger has a value of zero.
  423. */
  424. boolean isZero() {
  425. return (intLen == 0);
  426. }
  427. /**
  428. * Returns true iff this MutableBigInteger is even.
  429. */
  430. boolean isEven() {
  431. return (intLen == 0) || ((value[offset + intLen - 1] & 1) == 0);
  432. }
  433. /**
  434. * Returns true iff this MutableBigInteger is odd.
  435. */
  436. boolean isOdd() {
  437. return isZero() ? false : ((value[offset + intLen - 1] & 1) == 1);
  438. }
  439. /**
  440. * Returns true iff this MutableBigInteger is in normal form. A
  441. * MutableBigInteger is in normal form if it has no leading zeros
  442. * after the offset, and intLen + offset <= value.length.
  443. */
  444. boolean isNormal() {
  445. if (intLen + offset > value.length)
  446. return false;
  447. if (intLen == 0)
  448. return true;
  449. return (value[offset] != 0);
  450. }
  451. /**
  452. * Returns a String representation of this MutableBigInteger in radix 10.
  453. */
  454. public String toString() {
  455. BigInteger b = toBigInteger(1);
  456. return b.toString();
  457. }
  458. /**
  459. * Like {@link #rightShift(int)} but {@code n} can be greater than the length of the number.
  460. */
  461. void safeRightShift(int n) {
  462. if (n/32 >= intLen) {
  463. reset();
  464. } else {
  465. rightShift(n);
  466. }
  467. }
  468. /**
  469. * Right shift this MutableBigInteger n bits. The MutableBigInteger is left
  470. * in normal form.
  471. */
  472. void rightShift(int n) {
  473. if (intLen == 0)
  474. return;
  475. int nInts = n >>> 5;
  476. int nBits = n & 0x1F;
  477. this.intLen -= nInts;
  478. if (nBits == 0)
  479. return;
  480. int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
  481. if (nBits >= bitsInHighWord) {
  482. this.primitiveLeftShift(32 - nBits);
  483. this.intLen--;
  484. } else {
  485. primitiveRightShift(nBits);
  486. }
  487. }
  488. /**
  489. * Like {@link #leftShift(int)} but {@code n} can be zero.
  490. */
  491. void safeLeftShift(int n) {
  492. if (n > 0) {
  493. leftShift(n);
  494. }
  495. }
  496. /**
  497. * Left shift this MutableBigInteger n bits.
  498. */
  499. void leftShift(int n) {
  500. /*
  501. * If there is enough storage space in this MutableBigInteger already
  502. * the available space will be used. Space to the right of the used
  503. * ints in the value array is faster to utilize, so the extra space
  504. * will be taken from the right if possible.
  505. */
  506. if (intLen == 0)
  507. return;
  508. int nInts = n >>> 5;
  509. int nBits = n&0x1F;
  510. int bitsInHighWord = BigInteger.bitLengthForInt(value[offset]);
  511. // If shift can be done without moving words, do so
  512. if (n <= (32-bitsInHighWord)) {
  513. primitiveLeftShift(nBits);
  514. return;
  515. }
  516. int newLen = intLen + nInts +1;
  517. if (nBits <= (32-bitsInHighWord))
  518. newLen--;
  519. if (value.length < newLen) {
  520. // The array must grow
  521. int[] result = new int[newLen];
  522. for (int i=0; i < intLen; i++)
  523. result[i] = value[offset+i];
  524. setValue(result, newLen);
  525. } else if (value.length - offset >= newLen) {
  526. // Use space on right
  527. for(int i=0; i < newLen - intLen; i++)
  528. value[offset+intLen+i] = 0;
  529. } else {
  530. // Must use space on left
  531. for (int i=0; i < intLen; i++)
  532. value[i] = value[offset+i];
  533. for (int i=intLen; i < newLen; i++)
  534. value[i] = 0;
  535. offset = 0;
  536. }
  537. intLen = newLen;
  538. if (nBits == 0)
  539. return;
  540. if (nBits <= (32-bitsInHighWord))
  541. primitiveLeftShift(nBits);
  542. else
  543. primitiveRightShift(32 -nBits);
  544. }
  545. /**
  546. * A primitive used for division. This method adds in one multiple of the
  547. * divisor a back to the dividend result at a specified offset. It is used
  548. * when qhat was estimated too large, and must be adjusted.
  549. */
  550. private int divadd(int[] a, int[] result, int offset) {
  551. long carry = 0;
  552. for (int j=a.length-1; j >= 0; j--) {
  553. long sum = (a[j] & LONG_MASK) +
  554. (result[j+offset] & LONG_MASK) + carry;
  555. result[j+offset] = (int)sum;
  556. carry = sum >>> 32;
  557. }
  558. return (int)carry;
  559. }
  560. /**
  561. * This method is used for division. It multiplies an n word input a by one
  562. * word input x, and subtracts the n word product from q. This is needed
  563. * when subtracting qhat*divisor from dividend.
  564. */
  565. private int mulsub(int[] q, int[] a, int x, int len, int offset) {
  566. long xLong = x & LONG_MASK;
  567. long carry = 0;
  568. offset += len;
  569. for (int j=len-1; j >= 0; j--) {
  570. long product = (a[j] & LONG_MASK) * xLong + carry;
  571. long difference = q[offset] - product;
  572. q[offset--] = (int)difference;
  573. carry = (product >>> 32)
  574. + (((difference & LONG_MASK) >
  575. (((~(int)product) & LONG_MASK))) ? 1:0);
  576. }
  577. return (int)carry;
  578. }
  579. /**
  580. * The method is the same as mulsun, except the fact that q array is not
  581. * updated, the only result of the method is borrow flag.
  582. */
  583. private int mulsubBorrow(int[] q, int[] a, int x, int len, int offset) {
  584. long xLong = x & LONG_MASK;
  585. long carry = 0;
  586. offset += len;
  587. for (int j=len-1; j >= 0; j--) {
  588. long product = (a[j] & LONG_MASK) * xLong + carry;
  589. long difference = q[offset--] - product;
  590. carry = (product >>> 32)
  591. + (((difference & LONG_MASK) >
  592. (((~(int)product) & LONG_MASK))) ? 1:0);
  593. }
  594. return (int)carry;
  595. }
  596. /**
  597. * Right shift this MutableBigInteger n bits, where n is
  598. * less than 32.
  599. * Assumes that intLen > 0, n > 0 for speed
  600. */
  601. private final void primitiveRightShift(int n) {
  602. int[] val = value;
  603. int n2 = 32 - n;
  604. for (int i=offset+intLen-1, c=val[i]; i > offset; i--) {
  605. int b = c;
  606. c = val[i-1];
  607. val[i] = (c << n2) | (b >>> n);
  608. }
  609. val[offset] >>>= n;
  610. }
  611. /**
  612. * Left shift this MutableBigInteger n bits, where n is
  613. * less than 32.
  614. * Assumes that intLen > 0, n > 0 for speed
  615. */
  616. private final void primitiveLeftShift(int n) {
  617. int[] val = value;
  618. int n2 = 32 - n;
  619. for (int i=offset, c=val[i], m=i+intLen-1; i < m; i++) {
  620. int b = c;
  621. c = val[i+1];
  622. val[i] = (b << n) | (c >>> n2);
  623. }
  624. val[offset+intLen-1] <<= n;
  625. }
  626. /**
  627. * Returns a {@code BigInteger} equal to the {@code n}
  628. * low ints of this number.
  629. */
  630. private BigInteger getLower(int n) {
  631. if (isZero()) {
  632. return BigInteger.ZERO;
  633. } else if (intLen < n) {
  634. return toBigInteger(1);
  635. } else {
  636. // strip zeros
  637. int len = n;
  638. while (len > 0 && value[offset+intLen-len] == 0)
  639. len--;
  640. int sign = len > 0 ? 1 : 0;
  641. return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign);
  642. }
  643. }
  644. /**
  645. * Discards all ints whose index is greater than {@code n}.
  646. */
  647. private void keepLower(int n) {
  648. if (intLen >= n) {
  649. offset += intLen - n;
  650. intLen = n;
  651. }
  652. }
  653. /**
  654. * Adds the contents of two MutableBigInteger objects.The result
  655. * is placed within this MutableBigInteger.
  656. * The contents of the addend are not changed.
  657. */
  658. void add(MutableBigInteger addend) {
  659. int x = intLen;
  660. int y = addend.intLen;
  661. int resultLen = (intLen > addend.intLen ? intLen : addend.intLen);
  662. int[] result = (value.length < resultLen ? new int[resultLen] : value);
  663. int rstart = result.length-1;
  664. long sum;
  665. long carry = 0;
  666. // Add common parts of both numbers
  667. while(x > 0 && y > 0) {
  668. x--; y--;
  669. sum = (value[x+offset] & LONG_MASK) +
  670. (addend.value[y+addend.offset] & LONG_MASK) + carry;
  671. result[rstart--] = (int)sum;
  672. carry = sum >>> 32;
  673. }
  674. // Add remainder of the longer number
  675. while(x > 0) {
  676. x--;
  677. if (carry == 0 && result == value && rstart == (x + offset))
  678. return;
  679. sum = (value[x+offset] & LONG_MASK) + carry;
  680. result[rstart--] = (int)sum;
  681. carry = sum >>> 32;
  682. }
  683. while(y > 0) {
  684. y--;
  685. sum = (addend.value[y+addend.offset] & LONG_MASK) + carry;
  686. result[rstart--] = (int)sum;
  687. carry = sum >>> 32;
  688. }
  689. if (carry > 0) { // Result must grow in length
  690. resultLen++;
  691. if (result.length < resultLen) {
  692. int temp[] = new int[resultLen];
  693. // Result one word longer from carry-out; copy low-order
  694. // bits into new result.
  695. System.arraycopy(result, 0, temp, 1, result.length);
  696. temp[0] = 1;
  697. result = temp;
  698. } else {
  699. result[rstart--] = 1;
  700. }
  701. }
  702. value = result;
  703. intLen = resultLen;
  704. offset = result.length - resultLen;
  705. }
  706. /**
  707. * Adds the value of {@code addend} shifted {@code n} ints to the left.
  708. * Has the same effect as {@code addend.leftShift(32*ints); add(addend);}
  709. * but doesn't change the value of {@code addend}.
  710. */
  711. void addShifted(MutableBigInteger addend, int n) {
  712. if (addend.isZero()) {
  713. return;
  714. }
  715. int x = intLen;
  716. int y = addend.intLen + n;
  717. int resultLen = (intLen > y ? intLen : y);
  718. int[] result = (value.length < resultLen ? new int[resultLen] : value);
  719. int rstart = result.length-1;
  720. long sum;
  721. long carry = 0;
  722. // Add common parts of both numbers
  723. while (x > 0 && y > 0) {
  724. x--; y--;
  725. int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;
  726. sum = (value[x+offset] & LONG_MASK) +
  727. (bval & LONG_MASK) + carry;
  728. result[rstart--] = (int)sum;
  729. carry = sum >>> 32;
  730. }
  731. // Add remainder of the longer number
  732. while (x > 0) {
  733. x--;
  734. if (carry == 0 && result == value && rstart == (x + offset)) {
  735. return;
  736. }
  737. sum = (value[x+offset] & LONG_MASK) + carry;
  738. result[rstart--] = (int)sum;
  739. carry = sum >>> 32;
  740. }
  741. while (y > 0) {
  742. y--;
  743. int bval = y+addend.offset < addend.value.length ? addend.value[y+addend.offset] : 0;
  744. sum = (bval & LONG_MASK) + carry;
  745. result[rstart--] = (int)sum;
  746. carry = sum >>> 32;
  747. }
  748. if (carry > 0) { // Result must grow in length
  749. resultLen++;
  750. if (result.length < resultLen) {
  751. int temp[] = new int[resultLen];
  752. // Result one word longer from carry-out; copy low-order
  753. // bits into new result.
  754. System.arraycopy(result, 0, temp, 1, result.length);
  755. temp[0] = 1;
  756. result = temp;
  757. } else {
  758. result[rstart--] = 1;
  759. }
  760. }
  761. value = result;
  762. intLen = resultLen;
  763. offset = result.length - resultLen;
  764. }
  765. /**
  766. * Like {@link #addShifted(MutableBigInteger, int)} but {@code this.intLen} must
  767. * not be greater than {@code n}. In other words, concatenates {@code this}
  768. * and {@code addend}.
  769. */
  770. void addDisjoint(MutableBigInteger addend, int n) {
  771. if (addend.isZero())
  772. return;
  773. int x = intLen;
  774. int y = addend.intLen + n;
  775. int resultLen = (intLen > y ? intLen : y);
  776. int[] result;
  777. if (value.length < resultLen)
  778. result = new int[resultLen];
  779. else {
  780. result = value;
  781. Arrays.fill(value, offset+intLen, value.length, 0);
  782. }
  783. int rstart = result.length-1;
  784. // copy from this if needed
  785. System.arraycopy(value, offset, result, rstart+1-x, x);
  786. y -= x;
  787. rstart -= x;
  788. int len = Math.min(y, addend.value.length-addend.offset);
  789. System.arraycopy(addend.value, addend.offset, result, rstart+1-y, len);
  790. // zero the gap
  791. for (int i=rstart+1-y+len; i < rstart+1; i++)
  792. result[i] = 0;
  793. value = result;
  794. intLen = resultLen;
  795. offset = result.length - resultLen;
  796. }
  797. /**
  798. * Adds the low {@code n} ints of {@code addend}.
  799. */
  800. void addLower(MutableBigInteger addend, int n) {
  801. MutableBigInteger a = new MutableBigInteger(addend);
  802. if (a.offset + a.intLen >= n) {
  803. a.offset = a.offset + a.intLen - n;
  804. a.intLen = n;
  805. }
  806. a.normalize();
  807. add(a);
  808. }
  809. /**
  810. * Subtracts the smaller of this and b from the larger and places the
  811. * result into this MutableBigInteger.
  812. */
  813. int subtract(MutableBigInteger b) {
  814. MutableBigInteger a = this;
  815. int[] result = value;
  816. int sign = a.compare(b);
  817. if (sign == 0) {
  818. reset();
  819. return 0;
  820. }
  821. if (sign < 0) {
  822. MutableBigInteger tmp = a;
  823. a = b;
  824. b = tmp;
  825. }
  826. int resultLen = a.intLen;
  827. if (result.length < resultLen)
  828. result = new int[resultLen];
  829. long diff = 0;
  830. int x = a.intLen;
  831. int y = b.intLen;
  832. int rstart = result.length - 1;
  833. // Subtract common parts of both numbers
  834. while (y > 0) {
  835. x--; y--;
  836. diff = (a.value[x+a.offset] & LONG_MASK) -
  837. (b.value[y+b.offset] & LONG_MASK) - ((int)-(diff>>32));
  838. result[rstart--] = (int)diff;
  839. }
  840. // Subtract remainder of longer number
  841. while (x > 0) {
  842. x--;
  843. diff = (a.value[x+a.offset] & LONG_MASK) - ((int)-(diff>>32));
  844. result[rstart--] = (int)diff;
  845. }
  846. value = result;
  847. intLen = resultLen;
  848. offset = value.length - resultLen;
  849. normalize();
  850. return sign;
  851. }
  852. /**
  853. * Subtracts the smaller of a and b from the larger and places the result
  854. * into the larger. Returns 1 if the answer is in a, -1 if in b, 0 if no
  855. * operation was performed.
  856. */
  857. private int difference(MutableBigInteger b) {
  858. MutableBigInteger a = this;
  859. int sign = a.compare(b);
  860. if (sign == 0)
  861. return 0;
  862. if (sign < 0) {
  863. MutableBigInteger tmp = a;
  864. a = b;
  865. b = tmp;
  866. }
  867. long diff = 0;
  868. int x = a.intLen;
  869. int y = b.intLen;
  870. // Subtract common parts of both numbers
  871. while (y > 0) {
  872. x--; y--;
  873. diff = (a.value[a.offset+ x] & LONG_MASK) -
  874. (b.value[b.offset+ y] & LONG_MASK) - ((int)-(diff>>32));
  875. a.value[a.offset+x] = (int)diff;
  876. }
  877. // Subtract remainder of longer number
  878. while (x > 0) {
  879. x--;
  880. diff = (a.value[a.offset+ x] & LONG_MASK) - ((int)-(diff>>32));
  881. a.value[a.offset+x] = (int)diff;
  882. }
  883. a.normalize();
  884. return sign;
  885. }
  886. /**
  887. * Multiply the contents of two MutableBigInteger objects. The result is
  888. * placed into MutableBigInteger z. The contents of y are not changed.
  889. */
  890. void multiply(MutableBigInteger y, MutableBigInteger z) {
  891. int xLen = intLen;
  892. int yLen = y.intLen;
  893. int newLen = xLen + yLen;
  894. // Put z into an appropriate state to receive product
  895. if (z.value.length < newLen)
  896. z.value = new int[newLen];
  897. z.offset = 0;
  898. z.intLen = newLen;
  899. // The first iteration is hoisted out of the loop to avoid extra add
  900. long carry = 0;
  901. for (int j=yLen-1, k=yLen+xLen-1; j >= 0; j--, k--) {
  902. long product = (y.value[j+y.offset] & LONG_MASK) *
  903. (value[xLen-1+offset] & LONG_MASK) + carry;
  904. z.value[k] = (int)product;
  905. carry = product >>> 32;
  906. }
  907. z.value[xLen-1] = (int)carry;
  908. // Perform the multiplication word by word
  909. for (int i = xLen-2; i >= 0; i--) {
  910. carry = 0;
  911. for (int j=yLen-1, k=yLen+i; j >= 0; j--, k--) {
  912. long product = (y.value[j+y.offset] & LONG_MASK) *
  913. (value[i+offset] & LONG_MASK) +
  914. (z.value[k] & LONG_MASK) + carry;
  915. z.value[k] = (int)product;
  916. carry = product >>> 32;
  917. }
  918. z.value[i] = (int)carry;
  919. }
  920. // Remove leading zeros from product
  921. z.normalize();
  922. }
  923. /**
  924. * Multiply the contents of this MutableBigInteger by the word y. The
  925. * result is placed into z.
  926. */
  927. void mul(int y, MutableBigInteger z) {
  928. if (y == 1) {
  929. z.copyValue(this);
  930. return;
  931. }
  932. if (y == 0) {
  933. z.clear();
  934. return;
  935. }
  936. // Perform the multiplication word by word
  937. long ylong = y & LONG_MASK;
  938. int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1]
  939. : z.value);
  940. long carry = 0;
  941. for (int i = intLen-1; i >= 0; i--) {
  942. long product = ylong * (value[i+offset] & LONG_MASK) + carry;
  943. zval[i+1] = (int)product;
  944. carry = product >>> 32;
  945. }
  946. if (carry == 0) {
  947. z.offset = 1;
  948. z.intLen = intLen;
  949. } else {
  950. z.offset = 0;
  951. z.intLen = intLen + 1;
  952. zval[0] = (int)carry;
  953. }
  954. z.value = zval;
  955. }
  956. /**
  957. * This method is used for division of an n word dividend by a one word
  958. * divisor. The quotient is placed into quotient. The one word divisor is
  959. * specified by divisor.
  960. *
  961. * @return the remainder of the division is returned.
  962. *
  963. */
  964. int divideOneWord(int divisor, MutableBigInteger quotient) {
  965. long divisorLong = divisor & LONG_MASK;
  966. // Special case of one word dividend
  967. if (intLen == 1) {
  968. long dividendValue = value[offset] & LONG_MASK;
  969. int q = (int) (dividendValue / divisorLong);
  970. int r = (int) (dividendValue - q * divisorLong);
  971. quotient.value[0] = q;
  972. quotient.intLen = (q == 0) ? 0 : 1;
  973. quotient.offset = 0;
  974. return r;
  975. }
  976. if (quotient.value.length < intLen)
  977. quotient.value = new int[intLen];
  978. quotient.offset = 0;
  979. quotient.intLen = intLen;
  980. // Normalize the divisor
  981. int shift = Integer.numberOfLeadingZeros(divisor);
  982. int rem = value[offset];
  983. long remLong = rem & LONG_MASK;
  984. if (remLong < divisorLong) {
  985. quotient.value[0] = 0;
  986. } else {
  987. quotient.value[0] = (int)(remLong / divisorLong);
  988. rem = (int) (remLong - (quotient.value[0] * divisorLong));
  989. remLong = rem & LONG_MASK;
  990. }
  991. int xlen = intLen;
  992. while (--xlen > 0) {
  993. long dividendEstimate = (remLong << 32) |
  994. (value[offset + intLen - xlen] & LONG_MASK);
  995. int q;
  996. if (dividendEstimate >= 0) {
  997. q = (int) (dividendEstimate / divisorLong);
  998. rem = (int) (dividendEstimate - q * divisorLong);
  999. } else {
  1000. long tmp = divWord(dividendEstimate, divisor);
  1001. q = (int) (tmp & LONG_MASK);
  1002. rem = (int) (tmp >>> 32);
  1003. }
  1004. quotient.value[intLen - xlen] = q;
  1005. remLong = rem & LONG_MASK;
  1006. }
  1007. quotient.normalize();
  1008. // Unnormalize
  1009. if (shift > 0)
  1010. return rem % divisor;
  1011. else
  1012. return rem;
  1013. }
  1014. /**
  1015. * Calculates the quotient of this div b and places the quotient in the
  1016. * provided MutableBigInteger objects and the remainder object is returned.
  1017. *
  1018. */
  1019. MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient) {
  1020. return divide(b,quotient,true);
  1021. }
  1022. MutableBigInteger divide(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {
  1023. if (b.intLen < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD ||
  1024. intLen - b.intLen < BigInteger.BURNIKEL_ZIEGLER_OFFSET) {
  1025. return divideKnuth(b, quotient, needRemainder);
  1026. } else {
  1027. return divideAndRemainderBurnikelZiegler(b, quotient);
  1028. }
  1029. }
  1030. /**
  1031. * @see #divideKnuth(MutableBigInteger, MutableBigInteger, boolean)
  1032. */
  1033. MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient) {
  1034. return divideKnuth(b,quotient,true);
  1035. }
  1036. /**
  1037. * Calculates the quotient of this div b and places the quotient in the
  1038. * provided MutableBigInteger objects and the remainder object is returned.
  1039. *
  1040. * Uses Algorithm D in Knuth section 4.3.1.
  1041. * Many optimizations to that algorithm have been adapted from the Colin
  1042. * Plumb C library.
  1043. * It special cases one word divisors for speed. The content of b is not
  1044. * changed.
  1045. *
  1046. */
  1047. MutableBigInteger divideKnuth(MutableBigInteger b, MutableBigInteger quotient, boolean needRemainder) {
  1048. if (b.intLen == 0)
  1049. throw new ArithmeticException("BigInteger divide by zero");
  1050. // Dividend is zero
  1051. if (intLen == 0) {
  1052. quotient.intLen = quotient.offset = 0;
  1053. return needRemainder ? new MutableBigInteger() : null;
  1054. }
  1055. int cmp = compare(b);
  1056. // Dividend less than divisor
  1057. if (cmp < 0) {
  1058. quotient.intLen = quotient.offset = 0;
  1059. return needRemainder ? new MutableBigInteger(this) : null;
  1060. }
  1061. // Dividend equal to divisor
  1062. if (cmp == 0) {
  1063. quotient.value[0] = quotient.intLen = 1;
  1064. quotient.offset = 0;
  1065. return needRemainder ? new MutableBigInteger() : null;
  1066. }
  1067. quotient.clear();
  1068. // Special case one word divisor
  1069. if (b.intLen == 1) {
  1070. int r = divideOneWord(b.value[b.offset], quotient);
  1071. if(needRemainder) {
  1072. if (r == 0)
  1073. return new MutableBigInteger();
  1074. return new MutableBigInteger(r);
  1075. } else {
  1076. return null;
  1077. }
  1078. }
  1079. // Cancel common powers of two if we're above the KNUTH_POW2_* thresholds
  1080. if (intLen >= KNUTH_POW2_THRESH_LEN) {
  1081. int trailingZeroBits = Math.min(getLowestSetBit(), b.getLowestSetBit());
  1082. if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS*32) {
  1083. MutableBigInteger a = new MutableBigInteger(this);
  1084. b = new MutableBigInteger(b);
  1085. a.rightShift(trailingZeroBits);
  1086. b.rightShift(trailingZeroBits);
  1087. MutableBigInteger r = a.divideKnuth(b, quotient);
  1088. r.leftShift(trailingZeroBits);
  1089. return r;
  1090. }
  1091. }
  1092. return divideMagnitude(b, quotient, needRemainder);
  1093. }
  1094. /**
  1095. * Computes {@code this/b} and {@code this%b} using the
  1096. * <a href="http://cr.yp.to/bib/1998/burnikel.ps"> Burnikel-Ziegler algorithm</a>.
  1097. * This method implements algorithm 3 from pg. 9 of the Burnikel-Ziegler paper.
  1098. * The parameter beta was chosen to b 2<sup>32</sup> so almost all shifts are
  1099. * multiples of 32 bits.<br/>
  1100. * {@code this} and {@code b} must be nonnegative.
  1101. * @param b the divisor
  1102. * @param quotient output parameter for {@code this/b}
  1103. * @return the remainder
  1104. */
  1105. MutableBigInteger divideAndRemainderBurnikelZiegler(MutableBigInteger b, MutableBigInteger quotient) {
  1106. int r = intLen;
  1107. int s = b.intLen;
  1108. // Clear the quotient
  1109. quotient.offset = quotient.intLen = 0;
  1110. if (r < s) {
  1111. return this;
  1112. } else {
  1113. // Unlike Knuth division, we don't check for common powers of two here because
  1114. // BZ already runs faster if both numbers contain powers of two and cancelling them has no
  1115. // additional benefit.
  1116. // step 1: let m = min{2^k | (2^k)*BURNIKEL_ZIEGLER_THRESHOLD > s}
  1117. int m = 1 << (32-Integer.numberOfLeadingZeros(s/BigInteger.BURNIKEL_ZIEGLER_THRESHOLD));
  1118. int j = (s+m-1) / m; // step 2a: j = ceil(s/m)
  1119. int n = j * m; // step 2b: block length in 32-bit units
  1120. long n32 = 32L * n; // block length in bits
  1121. int sigma = (int) Math.max(0, n32 - b.bitLength()); // step 3: sigma = max{T | (2^T)*B < beta^n}
  1122. MutableBigInteger bShifted = new MutableBigInteger(b);
  1123. bShifted.safeLeftShift(sigma); // step 4a: shift b so its length is a multiple of n
  1124. MutableBigInteger aShifted = new MutableBigInteger (this);
  1125. aShifted.safeLeftShift(sigma); // step 4b: shift a by the same amount
  1126. // step 5: t is the number of blocks needed to accommodate a plus one additional bit
  1127. int t = (int) ((aShifted.bitLength()+n32) / n32);
  1128. if (t < 2) {
  1129. t = 2;
  1130. }
  1131. // step 6: conceptually split a into blocks a[t-1], ..., a[0]
  1132. MutableBigInteger a1 = aShifted.getBlock(t-1, t, n); // the most significant block of a
  1133. // step 7: z[t-2] = [a[t-1], a[t-2]]
  1134. MutableBigInteger z = aShifted.getBlock(t-2, t, n); // the second to most significant block
  1135. z.addDisjoint(a1, n); // z[t-2]
  1136. // do schoolbook division on blocks, dividing 2-block numbers by 1-block numbers
  1137. MutableBigInteger qi = new MutableBigInteger();
  1138. MutableBigInteger ri;
  1139. for (int i=t-2; i > 0; i--) {
  1140. // step 8a: compute (qi,ri) such that z=b*qi+ri
  1141. ri = z.divide2n1n(bShifted, qi);
  1142. // step 8b: z = [ri, a[i-1]]
  1143. z = aShifted.getBlock(i-1, t, n); // a[i-1]
  1144. z.addDisjoint(ri, n);
  1145. quotient.addShifted(qi, i*n); // update q (part of step 9)
  1146. }
  1147. // final iteration of step 8: do the loop one more time for i=0 but leave z unchanged
  1148. ri = z.divide2n1n(bShifted, qi);
  1149. quotient.add(qi);
  1150. ri.rightShift(sigma); // step 9: a and b were shifted, so shift back
  1151. return ri;
  1152. }
  1153. }
  1154. /**
  1155. * This method implements algorithm 1 from pg. 4 of the Burnikel-Ziegler paper.
  1156. * It divides a 2n-digit number by a n-digit number.<br/>
  1157. * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.
  1158. * <br/>
  1159. * {@code this} must be a nonnegative number such that {@code this.bitLength() <= 2*b.bitLength()}
  1160. * @param b a positive number such that {@code b.bitLength()} is even
  1161. * @param quotient output parameter for {@code this/b}
  1162. * @return {@code this%b}
  1163. */
  1164. private MutableBigInteger divide2n1n(MutableBigInteger b, MutableBigInteger quotient) {
  1165. int n = b.intLen;
  1166. // step 1: base case
  1167. if (n%2 != 0 || n < BigInteger.BURNIKEL_ZIEGLER_THRESHOLD) {
  1168. return divideKnuth(b, quotient);
  1169. }
  1170. // step 2: view this as [a1,a2,a3,a4] where each ai is n/2 ints or less
  1171. MutableBigInteger aUpper = new MutableBigInteger(this);
  1172. aUpper.safeRightShift(32*(n/2)); // aUpper = [a1,a2,a3]
  1173. keepLower(n/2); // this = a4
  1174. // step 3: q1=aUpper/b, r1=aUpper%b
  1175. MutableBigInteger q1 = new MutableBigInteger();
  1176. MutableBigInteger r1 = aUpper.divide3n2n(b, q1);
  1177. // step 4: quotient=[r1,this]/b, r2=[r1,this]%b
  1178. addDisjoint(r1, n/2); // this = [r1,this]
  1179. MutableBigInteger r2 = divide3n2n(b, quotient);
  1180. // step 5: let quotient=[q1,quotient] and return r2
  1181. quotient.addDisjoint(q1, n/2);
  1182. return r2;
  1183. }
  1184. /**
  1185. * This method implements algorithm 2 from pg. 5 of the Burnikel-Ziegler paper.
  1186. * It divides a 3n-digit number by a 2n-digit number.<br/>
  1187. * The parameter beta is 2<sup>32</sup> so all shifts are multiples of 32 bits.<br/>
  1188. * <br/>
  1189. * {@code this} must be a nonnegative number such that {@code 2*this.bitLength() <= 3*b.bitLength()}
  1190. * @param quotient output parameter for {@code this/b}
  1191. * @return {@code this%b}
  1192. */
  1193. private MutableBigInteger divide3n2n(MutableBigInteger b, MutableBigInteger quotient) {
  1194. int n = b.intLen / 2; // half the length of b in ints
  1195. // step 1: view this as [a1,a2,a3] where each ai is n ints or less; let a12=[a1,a2]
  1196. MutableBigInteger a12 = new MutableBigInteger(this);
  1197. a12.safeRightShift(32*n);
  1198. // step 2: view b as [b1,b2] where each bi is n ints or less
  1199. MutableBigInteger b1 = new MutableBigInteger(b);
  1200. b1.safeRightShift(n * 32);
  1201. BigInteger b2 = b.getLower(n);
  1202. MutableBigInteger r;
  1203. MutableBigInteger d;
  1204. if (compareShifted(b, n) < 0) {
  1205. // step 3a: if a1<b1, let quotient=a12/b1 and r=a12%b1
  1206. r = a12.divide2n1n(b1, quotient);
  1207. // step 4: d=quotient*b2
  1208. d = new MutableBigInteger(quotient.toBigInteger().multiply(b2));
  1209. } else {
  1210. // step 3b: if a1>=b1, let quotient=beta^n-1 and r=a12-b1*2^n+b1
  1211. quotient.ones(n);
  1212. a12.add(b1);
  1213. b1.leftShift(32*n);
  1214. a12.subtract(b1);
  1215. r = a12;
  1216. // step 4: d=quotient*b2=(b2 << 32*n) - b2
  1217. d = new MutableBigInteger(b2);
  1218. d.leftShift(32 * n);
  1219. d.subtract(new MutableBigInteger(b2));
  1220. }
  1221. // step 5: r = r*beta^n + a3 - d (paper says a4)
  1222. // However, don't subtract d until after the while loop so r doesn't become negative
  1223. r.leftShift(32 * n);
  1224. r.addLower(this, n);
  1225. // step 6: add b until r>=d
  1226. while (r.compare(d) < 0) {
  1227. r.add(b);
  1228. quotient.subtract(MutableBigInteger.ONE);
  1229. }
  1230. r.subtract(d);
  1231. return r;
  1232. }
  1233. /**
  1234. * Returns a {@code MutableBigInteger} containing {@code blockLength} ints from
  1235. * {@code this} number, starting at {@code index*blockLength}.<br/>
  1236. * Used by Burnikel-Ziegler division.
  1237. * @param index the block index
  1238. * @param numBlocks the total number of blocks in {@code this} number
  1239. * @param blockLength length of one block in units of 32 bits
  1240. * @return
  1241. */
  1242. private MutableBigInteger getBlock(int index, int numBlocks, int blockLength) {
  1243. int blockStart = index * blockLength;
  1244. if (blockStart >= intLen) {
  1245. return new MutableBigInteger();
  1246. }
  1247. int blockEnd;
  1248. if (index == numBlocks-1) {
  1249. blockEnd = intLen;
  1250. } else {
  1251. blockEnd = (index+1) * blockLength;
  1252. }
  1253. if (blockEnd > intLen) {
  1254. return new MutableBigInteger();
  1255. }
  1256. int[] newVal = Arrays.copyOfRange(value, offset+intLen-blockEnd, offset+intLen-blockStart);
  1257. return new MutableBigInteger(newVal);
  1258. }
  1259. /** @see BigInteger#bitLength() */
  1260. long bitLength() {
  1261. if (intLen == 0)
  1262. return 0;
  1263. return intLen*32L - Integer.numberOfLeadingZeros(value[offset]);
  1264. }
  1265. /**
  1266. * Internally used to calculate the quotient of this div v and places the
  1267. * quotient in the provided MutableBigInteger object and the remainder is
  1268. * returned.
  1269. *
  1270. * @return the remainder of the division will be returned.
  1271. */
  1272. long divide(long v, MutableBigInteger quotient) {
  1273. if (v == 0)
  1274. throw new ArithmeticException("BigInteger divide by zero");
  1275. // Dividend is zero
  1276. if (intLen == 0) {
  1277. quotient.intLen = quotient.offset = 0;
  1278. return 0;
  1279. }
  1280. if (v < 0)
  1281. v = -v;
  1282. int d = (int)(v >>> 32);
  1283. quotient.clear();
  1284. // Special case on word divisor
  1285. if (d == 0)
  1286. return divideOneWord((int)v, quotient) & LONG_MASK;
  1287. else {
  1288. return divideLongMagnitude(v, quotient).toLong();
  1289. }
  1290. }
  1291. private static void copyAndShift(int[] src, int srcFrom, int srcLen, int[] dst, int dstFrom, int shift) {
  1292. int n2 = 32 - shift;
  1293. int c=src[srcFrom];
  1294. for (int i=0; i < srcLen-1; i++) {
  1295. int b = c;
  1296. c = src[++srcFrom];
  1297. dst[dstFrom+i] = (b << shift) | (c >>> n2);
  1298. }
  1299. dst[dstFrom+srcLen-1] = c << shift;
  1300. }
  1301. /**
  1302. * Divide this MutableBigInteger by the divisor.
  1303. * The quotient will be placed into the provided quotient object &
  1304. * the remainder object is returned.
  1305. */
  1306. private MutableBigInteger divideMagnitude(MutableBigInteger div,
  1307. MutableBigInteger quotient,
  1308. boolean needRemainder ) {
  1309. // assert div.intLen > 1
  1310. // D1 normalize the divisor
  1311. int shift = Integer.numberOfLeadingZeros(div.value[div.offset]);
  1312. // Copy divisor value to protect divisor
  1313. final int dlen = div.intLen;
  1314. int[] divisor;
  1315. MutableBigInteger rem; // Remainder starts as dividend with space for a leading zero
  1316. if (shift > 0) {
  1317. divisor = new int[dlen];
  1318. copyAndShift(div.value,div.offset,dlen,divisor,0,shift);
  1319. if (Integer.numberOfLeadingZeros(value[offset]) >= shift) {
  1320. int[] remarr = new int[intLen + 1];
  1321. rem = new MutableBigInteger(remarr);
  1322. rem.intLen = intLen;
  1323. rem.offset = 1;
  1324. copyAndShift(value,offset,intLen,remarr,1,shift);
  1325. } else {
  1326. int[] remarr = new int[intLen + 2];
  1327. rem = new MutableBigInteger(remarr);
  1328. rem.intLen = intLen+1;
  1329. rem.offset = 1;
  1330. int rFrom = offset;
  1331. int c=0;
  1332. int n2 = 32 - shift;
  1333. for (int i=1; i < intLen+1; i++,rFrom++) {
  1334. int b = c;
  1335. c = value[rFrom];
  1336. remarr[i] = (b << shift) | (c >>> n2);
  1337. }
  1338. remarr[intLen+1] = c << shift;
  1339. }
  1340. } else {
  1341. divisor = Arrays.copyOfRange(div.value, div.offset, div.offset + div.intLen);
  1342. rem = new MutableBigInteger(new int[intLen + 1]);
  1343. System.arraycopy(value, offset, rem.value, 1, intLen);
  1344. rem.intLen = intLen;
  1345. rem.offset = 1;
  1346. }
  1347. int nlen = rem.intLen;
  1348. // Set the quotient size
  1349. final int limit = nlen - dlen + 1;
  1350. if (quotient.value.length < limit) {
  1351. quotient.value = new int[limit];
  1352. quotient.offset = 0;
  1353. }
  1354. quotient.intLen = limit;
  1355. int[] q = quotient.value;
  1356. // Must insert leading 0 in rem if its length did not change
  1357. if (rem.intLen == nlen) {
  1358. rem.offset = 0;
  1359. rem.value[0] = 0;
  1360. rem.intLen++;
  1361. }
  1362. int dh = divisor[0];
  1363. long dhLong = dh & LONG_MASK;
  1364. int dl = divisor[1];
  1365. // D2 Initialize j
  1366. for (int j=0; j < limit-1; j++) {
  1367. // D3 Calculate qhat
  1368. // estimate qhat
  1369. int qhat = 0;
  1370. int qrem = 0;
  1371. boolean skipCorrection = false;
  1372. int nh = rem.value[j+rem.offset];
  1373. int nh2 = nh + 0x80000000;
  1374. int nm = rem.value[j+1+rem.offset];
  1375. if (nh == dh) {
  1376. qhat = ~0;
  1377. qrem = nh + nm;
  1378. skipCorrection = qrem + 0x80000000 < nh2;
  1379. } else {
  1380. long nChunk = (((long)nh) << 32) | (nm & LONG_MASK);
  1381. if (nChunk >= 0) {
  1382. qhat = (int) (nChunk / dhLong);
  1383. qrem = (int) (nChunk - (qhat * dhLong));
  1384. } else {
  1385. long tmp = divWord(nChunk, dh);
  1386. qhat = (int) (tmp & LONG_MASK);
  1387. qrem = (int) (tmp >>> 32);
  1388. }
  1389. }
  1390. if (qhat == 0)
  1391. continue;
  1392. if (!skipCorrection) { // Correct qhat
  1393. long nl = rem.value[j+2+rem.offset] & LONG_MASK;
  1394. long rs = ((qrem & LONG_MASK) << 32) | nl;
  1395. long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
  1396. if (unsignedLongCompare(estProduct, rs)) {
  1397. qhat--;
  1398. qrem = (int)((qrem & LONG_MASK) + dhLong);
  1399. if ((qrem & LONG_MASK) >= dhLong) {
  1400. estProduct -= (dl & LONG_MASK);
  1401. rs = ((qrem & LONG_MASK) << 32) | nl;
  1402. if (unsignedLongCompare(estProduct, rs))
  1403. qhat--;
  1404. }
  1405. }
  1406. }
  1407. // D4 Multiply and subtract
  1408. rem.value[j+rem.offset] = 0;
  1409. int borrow = mulsub(rem.value, divisor, qhat, dlen, j+rem.offset);
  1410. // D5 Test remainder
  1411. if (borrow + 0x80000000 > nh2) {
  1412. // D6 Add back
  1413. divadd(divisor, rem.value, j+1+rem.offset);
  1414. qhat--;
  1415. }
  1416. // Store the quotient digit
  1417. q[j] = qhat;
  1418. } // D7 loop on j
  1419. // D3 Calculate qhat
  1420. // estimate qhat
  1421. int qhat = 0;
  1422. int qrem = 0;
  1423. boolean skipCorrection = false;
  1424. int nh = rem.value[limit - 1 + rem.offset];
  1425. int nh2 = nh + 0x80000000;
  1426. int nm = rem.value[limit + rem.offset];
  1427. if (nh == dh) {
  1428. qhat = ~0;
  1429. qrem = nh + nm;
  1430. skipCorrection = qrem + 0x80000000 < nh2;
  1431. } else {
  1432. long nChunk = (((long) nh) << 32) | (nm & LONG_MASK);
  1433. if (nChunk >= 0) {
  1434. qhat = (int) (nChunk / dhLong);
  1435. qrem = (int) (nChunk - (qhat * dhLong));
  1436. } else {
  1437. long tmp = divWord(nChunk, dh);
  1438. qhat = (int) (tmp & LONG_MASK);
  1439. qrem = (int) (tmp >>> 32);
  1440. }
  1441. }
  1442. if (qhat != 0) {
  1443. if (!skipCorrection) { // Correct qhat
  1444. long nl = rem.value[limit + 1 + rem.offset] & LONG_MASK;
  1445. long rs = ((qrem & LONG_MASK) << 32) | nl;
  1446. long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
  1447. if (unsignedLongCompare(estProduct, rs)) {
  1448. qhat--;
  1449. qrem = (int) ((qrem & LONG_MASK) + dhLong);
  1450. if ((qrem & LONG_MASK) >= dhLong) {
  1451. estProduct -= (dl & LONG_MASK);
  1452. rs = ((qrem & LONG_MASK) << 32) | nl;
  1453. if (unsignedLongCompare(estProduct, rs))
  1454. qhat--;
  1455. }
  1456. }
  1457. }
  1458. // D4 Multiply and subtract
  1459. int borrow;
  1460. rem.value[limit - 1 + rem.offset] = 0;
  1461. if(needRemainder)
  1462. borrow = mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);
  1463. else
  1464. borrow = mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset);
  1465. // D5 Test remainder
  1466. if (borrow + 0x80000000 > nh2) {
  1467. // D6 Add back
  1468. if(needRemainder)
  1469. divadd(divisor, rem.value, limit - 1 + 1 + rem.offset);
  1470. qhat--;
  1471. }
  1472. // Store the quotient digit
  1473. q[(limit - 1)] = qhat;
  1474. }
  1475. if (needRemainder) {
  1476. // D8 Unnormalize
  1477. if (shift > 0)
  1478. rem.rightShift(shift);
  1479. rem.normalize();
  1480. }
  1481. quotient.normalize();
  1482. return needRemainder ? rem : null;
  1483. }
  1484. /**
  1485. * Divide this MutableBigInteger by the divisor represented by positive long
  1486. * value. The quotient will be placed into the provided quotient object &
  1487. * the remainder object is returned.
  1488. */
  1489. private MutableBigInteger divideLongMagnitude(long ldivisor, MutableBigInteger quotient) {
  1490. // Remainder starts as dividend with space for a leading zero
  1491. MutableBigInteger rem = new MutableBigInteger(new int[intLen + 1]);
  1492. System.arraycopy(value, offset, rem.value, 1, intLen);
  1493. rem.intLen = intLen;
  1494. rem.offset = 1;
  1495. int nlen = rem.intLen;
  1496. int limit = nlen - 2 + 1;
  1497. if (quotient.value.length < limit) {
  1498. quotient.value = new int[limit];
  1499. quotient.offset = 0;
  1500. }
  1501. quotient.intLen = limit;
  1502. int[] q = quotient.value;
  1503. // D1 normalize the divisor
  1504. int shift = Long.numberOfLeadingZeros(ldivisor);
  1505. if (shift > 0) {
  1506. ldivisor<<=shift;
  1507. rem.leftShift(shift);
  1508. }
  1509. // Must insert leading 0 in rem if its length did not change
  1510. if (rem.intLen == nlen) {
  1511. rem.offset = 0;
  1512. rem.value[0] = 0;
  1513. rem.intLen++;
  1514. }
  1515. int dh = (int)(ldivisor >>> 32);
  1516. long dhLong = dh & LONG_MASK;
  1517. int dl = (int)(ldivisor & LONG_MASK);
  1518. // D2 Initialize j
  1519. for (int j = 0; j < limit; j++) {
  1520. // D3 Calculate qhat
  1521. // estimate qhat
  1522. int qhat = 0;
  1523. int qrem = 0;
  1524. boolean skipCorrection = false;
  1525. int nh = rem.value[j + rem.offset];
  1526. int nh2 = nh + 0x80000000;
  1527. int nm = rem.value[j + 1 + rem.offset];
  1528. if (nh == dh) {
  1529. qhat = ~0;
  1530. qrem = nh + nm;
  1531. skipCorrection = qrem + 0x80000000 < nh2;
  1532. } else {
  1533. long nChunk = (((long) nh) << 32) | (nm & LONG_MASK);
  1534. if (nChunk >= 0) {
  1535. qhat = (int) (nChunk / dhLong);
  1536. qrem = (int) (nChunk - (qhat * dhLong));
  1537. } else {
  1538. long tmp = divWord(nChunk, dh);
  1539. qhat =(int)(tmp & LONG_MASK);
  1540. qrem = (int)(tmp>>>32);
  1541. }
  1542. }
  1543. if (qhat == 0)
  1544. continue;
  1545. if (!skipCorrection) { // Correct qhat
  1546. long nl = rem.value[j + 2 + rem.offset] & LONG_MASK;
  1547. long rs = ((qrem & LONG_MASK) << 32) | nl;
  1548. long estProduct = (dl & LONG_MASK) * (qhat & LONG_MASK);
  1549. if (unsignedLongCompare(estProduct, rs)) {
  1550. qhat--;
  1551. qrem = (int) ((qrem & LONG_MASK) + dhLong);
  1552. if ((qrem & LONG_MASK) >= dhLong) {
  1553. estProduct -= (dl & LONG_MASK);
  1554. rs = ((qrem & LONG_MASK) << 32) | nl;
  1555. if (unsignedLongCompare(estProduct, rs))
  1556. qhat--;
  1557. }
  1558. }
  1559. }
  1560. // D4 Multiply and subtract
  1561. rem.value[j + rem.offset] = 0;
  1562. int borrow = mulsubLong(rem.value, dh, dl, qhat, j + rem.offset);
  1563. // D5 Test remainder
  1564. if (borrow + 0x80000000 > nh2) {
  1565. // D6 Add back
  1566. divaddLong(dh,dl, rem.value, j + 1 + rem.offset);
  1567. qhat--;
  1568. }
  1569. // Store the quotient digit
  1570. q[j] = qhat;
  1571. } // D7 loop on j
  1572. // D8 Unnormalize
  1573. if (shift > 0)
  1574. rem.rightShift(shift);
  1575. quotient.normalize();
  1576. rem.normalize();
  1577. return rem;
  1578. }
  1579. /**
  1580. * A primitive used for division by long.
  1581. * Specialized version of the method divadd.
  1582. * dh is a high part of the divisor, dl is a low part
  1583. */
  1584. private int divaddLong(int dh, int dl, int[] result, int offset) {
  1585. long carry = 0;
  1586. long sum = (dl & LONG_MASK) + (result[1+offset] & LONG_MASK);
  1587. result[1+offset] = (int)sum;
  1588. sum = (dh & LONG_MASK) + (result[offset] & LONG_MASK) + carry;
  1589. result[offset] = (int)sum;
  1590. carry = sum >>> 32;
  1591. return (int)carry;
  1592. }
  1593. /**
  1594. * This method is used for division by long.
  1595. * Specialized version of the method sulsub.
  1596. * dh is a high part of the divisor, dl is a low part
  1597. */
  1598. private int mulsubLong(int[] q, int dh, int dl, int x, int offset) {
  1599. long xLong = x & LONG_MASK;
  1600. offset += 2;
  1601. long product = (dl & LONG_MASK) * xLong;
  1602. long difference = q[offset] - product;
  1603. q[offset--] = (int)difference;
  1604. long carry = (product >>> 32)
  1605. + (((difference & LONG_MASK) >
  1606. (((~(int)product) & LONG_MASK))) ? 1:0);
  1607. product = (dh & LONG_MASK) * xLong + carry;
  1608. difference = q[offset] - product;
  1609. q[offset--] = (int)difference;
  1610. carry = (product >>> 32)
  1611. + (((difference & LONG_MASK) >
  1612. (((~(int)product) & LONG_MASK))) ? 1:0);
  1613. return (int)carry;
  1614. }
  1615. /**
  1616. * Compare two longs as if they were unsigned.
  1617. * Returns true iff one is bigger than two.
  1618. */
  1619. private boolean unsignedLongCompare(long one, long two) {
  1620. return (one+Long.MIN_VALUE) > (two+Long.MIN_VALUE);
  1621. }
  1622. /**
  1623. * This method divides a long quantity by an int to estimate
  1624. * qhat for two multi precision numbers. It is used when
  1625. * the signed value of n is less than zero.
  1626. * Returns long value where high 32 bits contain remainder value and
  1627. * low 32 bits contain quotient value.
  1628. */
  1629. static long divWord(long n, int d) {
  1630. long dLong = d & LONG_MASK;
  1631. long r;
  1632. long q;
  1633. if (dLong == 1) {
  1634. q = (int)n;
  1635. r = 0;
  1636. return (r << 32) | (q & LONG_MASK);
  1637. }
  1638. // Approximate the quotient and remainder
  1639. q = (n >>> 1) / (dLong >>> 1);
  1640. r = n - q*dLong;
  1641. // Correct the approximation
  1642. while (r < 0) {
  1643. r += dLong;
  1644. q--;
  1645. }
  1646. while (r >= dLong) {
  1647. r -= dLong;
  1648. q++;
  1649. }
  1650. // n - q*dlong == r && 0 <= r <dLong, hence we're done.
  1651. return (r << 32) | (q & LONG_MASK);
  1652. }
  1653. /**
  1654. * Calculate GCD of this and b. This and b are changed by the computation.
  1655. */
  1656. MutableBigInteger hybridGCD(MutableBigInteger b) {
  1657. // Use Euclid's algorithm until the numbers are approximately the
  1658. // same length, then use the binary GCD algorithm to find the GCD.
  1659. MutableBigInteger a = this;
  1660. MutableBigInteger q = new MutableBigInteger();
  1661. while (b.intLen != 0) {
  1662. if (Math.abs(a.intLen - b.intLen) < 2)
  1663. return a.binaryGCD(b);
  1664. MutableBigInteger r = a.divide(b, q);
  1665. a = b;
  1666. b = r;
  1667. }
  1668. return a;
  1669. }
  1670. /**
  1671. * Calculate GCD of this and v.
  1672. * Assumes that this and v are not zero.
  1673. */
  1674. private MutableBigInteger binaryGCD(MutableBigInteger v) {
  1675. // Algorithm B from Knuth section 4.5.2
  1676. MutableBigInteger u = this;
  1677. MutableBigInteger r = new MutableBigInteger();
  1678. // step B1
  1679. int s1 = u.getLowestSetBit();
  1680. int s2 = v.getLowestSetBit();
  1681. int k = (s1 < s2) ? s1 : s2;
  1682. if (k != 0) {
  1683. u.rightShift(k);
  1684. v.rightShift(k);
  1685. }
  1686. // step B2
  1687. boolean uOdd = (k == s1);
  1688. MutableBigInteger t = uOdd ? v: u;
  1689. int tsign = uOdd ? -1 : 1;
  1690. int lb;
  1691. while ((lb = t.getLowestSetBit()) >= 0) {
  1692. // steps B3 and B4
  1693. t.rightShift(lb);
  1694. // step B5
  1695. if (tsign > 0)
  1696. u = t;
  1697. else
  1698. v = t;
  1699. // Special case one word numbers
  1700. if (u.intLen < 2 && v.intLen < 2) {
  1701. int x = u.value[u.offset];
  1702. int y = v.value[v.offset];
  1703. x = binaryGcd(x, y);
  1704. r.value[0] = x;
  1705. r.intLen = 1;
  1706. r.offset = 0;
  1707. if (k > 0)
  1708. r.leftShift(k);
  1709. return r;
  1710. }
  1711. // step B6
  1712. if ((tsign = u.difference(v)) == 0)
  1713. break;
  1714. t = (tsign >= 0) ? u : v;
  1715. }
  1716. if (k > 0)
  1717. u.leftShift(k);
  1718. return u;
  1719. }
  1720. /**
  1721. * Calculate GCD of a and b interpreted as unsigned integers.
  1722. */
  1723. static int binaryGcd(int a, int b) {
  1724. if (b == 0)
  1725. return a;
  1726. if (a == 0)
  1727. return b;
  1728. // Right shift a & b till their last bits equal to 1.
  1729. int aZeros = Integer.numberOfTrailingZeros(a);
  1730. int bZeros = Integer.numberOfTrailingZeros(b);
  1731. a >>>= aZeros;
  1732. b >>>= bZeros;
  1733. int t = (aZeros < bZeros ? aZeros : bZeros);
  1734. while (a != b) {
  1735. if ((a+0x80000000) > (b+0x80000000)) { // a > b as unsigned
  1736. a -= b;
  1737. a >>>= Integer.numberOfTrailingZeros(a);
  1738. } else {
  1739. b -= a;
  1740. b >>>= Integer.numberOfTrailingZeros(b);
  1741. }
  1742. }
  1743. return a<<t;
  1744. }
  1745. /**
  1746. * Returns the modInverse of this mod p. This and p are not affected by
  1747. * the operation.
  1748. */
  1749. MutableBigInteger mutableModInverse(MutableBigInteger p) {
  1750. // Modulus is odd, use Schroeppel's algorithm
  1751. if (p.isOdd())
  1752. return modInverse(p);
  1753. // Base and modulus are even, throw exception
  1754. if (isEven())
  1755. throw new ArithmeticException("BigInteger not invertible.");
  1756. // Get even part of modulus expressed as a power of 2
  1757. int powersOf2 = p.getLowestSetBit();
  1758. // Construct odd part of modulus
  1759. MutableBigInteger oddMod = new MutableBigInteger(p);
  1760. oddMod.rightShift(powersOf2);
  1761. if (oddMod.isOne())
  1762. return modInverseMP2(powersOf2);
  1763. // Calculate 1/a mod oddMod
  1764. MutableBigInteger oddPart = modInverse(oddMod);
  1765. // Calculate 1/a mod evenMod
  1766. MutableBigInteger evenPart = modInverseMP2(powersOf2);
  1767. // Combine the results using Chinese Remainder Theorem
  1768. MutableBigInteger y1 = modInverseBP2(oddMod, powersOf2);
  1769. MutableBigInteger y2 = oddMod.modInverseMP2(powersOf2);
  1770. MutableBigInteger temp1 = new MutableBigInteger();
  1771. MutableBigInteger temp2 = new MutableBigInteger();
  1772. MutableBigInteger result = new MutableBigInteger();
  1773. oddPart.leftShift(powersOf2);
  1774. oddPart.multiply(y1, result);
  1775. evenPart.multiply(oddMod, temp1);
  1776. temp1.multiply(y2, temp2);
  1777. result.add(temp2);
  1778. return result.divide(p, temp1);
  1779. }
  1780. /*
  1781. * Calculate the multiplicative inverse of this mod 2^k.
  1782. */
  1783. MutableBigInteger modInverseMP2(int k) {
  1784. if (isEven())
  1785. throw new ArithmeticException("Non-invertible. (GCD != 1)");
  1786. if (k > 64)
  1787. return euclidModInverse(k);
  1788. int t = inverseMod32(value[offset+intLen-1]);
  1789. if (k < 33) {
  1790. t = (k == 32 ? t : t & ((1 << k) - 1));
  1791. return new MutableBigInteger(t);
  1792. }
  1793. long pLong = (value[offset+intLen-1] & LONG_MASK);
  1794. if (intLen > 1)
  1795. pLong |= ((long)value[offset+intLen-2] << 32);
  1796. long tLong = t & LONG_MASK;
  1797. tLong = tLong * (2 - pLong * tLong); // 1 more Newton iter step
  1798. tLong = (k == 64 ? tLong : tLong & ((1L << k) - 1));
  1799. MutableBigInteger result = new MutableBigInteger(new int[2]);
  1800. result.value[0] = (int)(tLong >>> 32);
  1801. result.value[1] = (int)tLong;
  1802. result.intLen = 2;
  1803. result.normalize();
  1804. return result;
  1805. }
  1806. /**
  1807. * Returns the multiplicative inverse of val mod 2^32. Assumes val is odd.
  1808. */
  1809. static class SignedMutableBigInteger extends MutableBigInteger {
  1810. /**
  1811. * The sign of this MutableBigInteger.
  1812. */
  1813. int sign = 1;
  1814. // Constructors
  1815. /**
  1816. * The default constructor. An empty MutableBigInteger is created with
  1817. * a one word capacity.
  1818. */
  1819. SignedMutableBigInteger() {
  1820. super();
  1821. }
  1822. /**
  1823. * Construct a new MutableBigInteger with a magnitude specified by
  1824. * the int val.
  1825. */
  1826. SignedMutableBigInteger(int val) {
  1827. super(val);
  1828. }
  1829. /**
  1830. * Construct a new MutableBigInteger with a magnitude equal to the
  1831. * specified MutableBigInteger.
  1832. */
  1833. SignedMutableBigInteger(MutableBigInteger val) {
  1834. super(val);
  1835. }
  1836. // Arithmetic Operations
  1837. /**
  1838. * Signed addition built upon unsigned add and subtract.
  1839. */
  1840. void signedAdd(SignedMutableBigInteger addend) {
  1841. if (sign == addend.sign)
  1842. add(addend);
  1843. else
  1844. sign = sign * subtract(addend);
  1845. }
  1846. /**
  1847. * Signed addition built upon unsigned add and subtract.
  1848. */
  1849. void signedAdd(MutableBigInteger addend) {
  1850. if (sign == 1)
  1851. add(addend);
  1852. else
  1853. sign = sign * subtract(addend);
  1854. }
  1855. /**
  1856. * Signed subtraction built upon unsigned add and subtract.
  1857. */
  1858. void signedSubtract(SignedMutableBigInteger addend) {
  1859. if (sign == addend.sign)
  1860. sign = sign * subtract(addend);
  1861. else
  1862. add(addend);
  1863. }
  1864. /**
  1865. * Signed subtraction built upon unsigned add and subtract.
  1866. */
  1867. void signedSubtract(MutableBigInteger addend) {
  1868. if (sign == 1)
  1869. sign = sign * subtract(addend);
  1870. else
  1871. add(addend);
  1872. if (intLen == 0)
  1873. sign = 1;
  1874. }
  1875. /**
  1876. * Print out the first intLen ints of this MutableBigInteger's value
  1877. * array starting at offset.
  1878. */
  1879. public String toString() {
  1880. return this.toBigInteger(sign).toString();
  1881. }
  1882. }
  1883. static int inverseMod32(int val) {
  1884. // Newton's iteration!
  1885. int t = val;
  1886. t *= 2 - val*t;
  1887. t *= 2 - val*t;
  1888. t *= 2 - val*t;
  1889. t *= 2 - val*t;
  1890. return t;
  1891. }
  1892. /**
  1893. * Returns the multiplicative inverse of val mod 2^64. Assumes val is odd.
  1894. */
  1895. static long inverseMod64(long val) {
  1896. // Newton's iteration!
  1897. long t = val;
  1898. t *= 2 - val*t;
  1899. t *= 2 - val*t;
  1900. t *= 2 - val*t;
  1901. t *= 2 - val*t;
  1902. t *= 2 - val*t;
  1903. assert(t * val == 1);
  1904. return t;
  1905. }
  1906. /**
  1907. * Calculate the multiplicative inverse of 2^k mod mod, where mod is odd.
  1908. */
  1909. static MutableBigInteger modInverseBP2(MutableBigInteger mod, int k) {
  1910. // Copy the mod to protect original
  1911. return fixup(new MutableBigInteger(1), new MutableBigInteger(mod), k);
  1912. }
  1913. /**
  1914. * Calculate the multiplicative inverse of this mod mod, where mod is odd.
  1915. * This and mod are not changed by the calculation.
  1916. *
  1917. * This method implements an algorithm due to Richard Schroeppel, that uses
  1918. * the same intermediate representation as Montgomery Reduction
  1919. * ("Montgomery Form"). The algorithm is described in an unpublished
  1920. * manuscript entitled "Fast Modular Reciprocals."
  1921. */
  1922. private MutableBigInteger modInverse(MutableBigInteger mod) {
  1923. MutableBigInteger p = new MutableBigInteger(mod);
  1924. MutableBigInteger f = new MutableBigInteger(this);
  1925. MutableBigInteger g = new MutableBigInteger(p);
  1926. SignedMutableBigInteger c = new SignedMutableBigInteger(1);
  1927. SignedMutableBigInteger d = new SignedMutableBigInteger();
  1928. MutableBigInteger temp = null;
  1929. SignedMutableBigInteger sTemp = null;
  1930. int k = 0;
  1931. // Right shift f k times until odd, left shift d k times
  1932. if (f.isEven()) {
  1933. int trailingZeros = f.getLowestSetBit();
  1934. f.rightShift(trailingZeros);
  1935. d.leftShift(trailingZeros);
  1936. k = trailingZeros;
  1937. }
  1938. // The Almost Inverse Algorithm
  1939. while (!f.isOne()) {
  1940. // If gcd(f, g) != 1, number is not invertible modulo mod
  1941. if (f.isZero())
  1942. throw new ArithmeticException("BigInteger not invertible.");
  1943. // If f < g exchange f, g and c, d
  1944. if (f.compare(g) < 0) {
  1945. temp = f; f = g; g = temp;
  1946. sTemp = d; d = c; c = sTemp;
  1947. }
  1948. // If f == g (mod 4)
  1949. if (((f.value[f.offset + f.intLen - 1] ^
  1950. g.value[g.offset + g.intLen - 1]) & 3) == 0) {
  1951. f.subtract(g);
  1952. c.signedSubtract(d);
  1953. } else { // If f != g (mod 4)
  1954. f.add(g);
  1955. c.signedAdd(d);
  1956. }
  1957. // Right shift f k times until odd, left shift d k times
  1958. int trailingZeros = f.getLowestSetBit();
  1959. f.rightShift(trailingZeros);
  1960. d.leftShift(trailingZeros);
  1961. k += trailingZeros;
  1962. }
  1963. while (c.sign < 0)
  1964. c.signedAdd(p);
  1965. return fixup(c, p, k);
  1966. }
  1967. /**
  1968. * The Fixup Algorithm
  1969. * Calculates X such that X = C * 2^(-k) (mod P)
  1970. * Assumes C<P and P is odd.
  1971. */
  1972. static MutableBigInteger fixup(MutableBigInteger c, MutableBigInteger p,
  1973. int k) {
  1974. MutableBigInteger temp = new MutableBigInteger();
  1975. // Set r to the multiplicative inverse of p mod 2^32
  1976. int r = -inverseMod32(p.value[p.offset+p.intLen-1]);
  1977. for (int i=0, numWords = k >> 5; i < numWords; i++) {
  1978. // V = R * c (mod 2^j)
  1979. int v = r * c.value[c.offset + c.intLen-1];
  1980. // c = c + (v * p)
  1981. p.mul(v, temp);
  1982. c.add(temp);
  1983. // c = c / 2^j
  1984. c.intLen--;
  1985. }
  1986. int numBits = k & 0x1f;
  1987. if (numBits != 0) {
  1988. // V = R * c (mod 2^j)
  1989. int v = r * c.value[c.offset + c.intLen-1];
  1990. v &= ((1<<numBits) - 1);
  1991. // c = c + (v * p)
  1992. p.mul(v, temp);
  1993. c.add(temp);
  1994. // c = c / 2^j
  1995. c.rightShift(numBits);
  1996. }
  1997. // In theory, c may be greater than p at this point (Very rare!)
  1998. while (c.compare(p) >= 0)
  1999. c.subtract(p);
  2000. return c;
  2001. }
  2002. /**
  2003. * Uses the extended Euclidean algorithm to compute the modInverse of base
  2004. * mod a modulus that is a power of 2. The modulus is 2^k.
  2005. */
  2006. MutableBigInteger euclidModInverse(int k) {
  2007. MutableBigInteger b = new MutableBigInteger(1);
  2008. b.leftShift(k);
  2009. MutableBigInteger mod = new MutableBigInteger(b);
  2010. MutableBigInteger a = new MutableBigInteger(this);
  2011. MutableBigInteger q = new MutableBigInteger();
  2012. MutableBigInteger r = b.divide(a, q);
  2013. MutableBigInteger swapper = b;
  2014. // swap b & r
  2015. b = r;
  2016. r = swapper;
  2017. MutableBigInteger t1 = new MutableBigInteger(q);
  2018. MutableBigInteger t0 = new MutableBigInteger(1);
  2019. MutableBigInteger temp = new MutableBigInteger();
  2020. while (!b.isOne()) {
  2021. r = a.divide(b, q);
  2022. if (r.intLen == 0)
  2023. throw new ArithmeticException("BigInteger not invertible.");
  2024. swapper = r;
  2025. a = swapper;
  2026. if (q.intLen == 1)
  2027. t1.mul(q.value[q.offset], temp);
  2028. else
  2029. q.multiply(t1, temp);
  2030. swapper = q;
  2031. q = temp;
  2032. temp = swapper;
  2033. t0.add(q);
  2034. if (a.isOne())
  2035. return t0;
  2036. r = b.divide(a, q);
  2037. if (r.intLen == 0)
  2038. throw new ArithmeticException("BigInteger not invertible.");
  2039. swapper = b;
  2040. b = r;
  2041. if (q.intLen == 1)
  2042. t0.mul(q.value[q.offset], temp);
  2043. else
  2044. q.multiply(t0, temp);
  2045. swapper = q; q = temp; temp = swapper;
  2046. t1.add(q);
  2047. }
  2048. mod.subtract(t1);
  2049. return mod;
  2050. }
  2051. }