BigInteger.java 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374
  1. #include <vector>
  2. #include <cstdint>
  3. #include <cassert>
  4. using std::uint64_t;
  5. class BigInteger{
  6. const int signum;
  7. std::vector<int> mag;
  8. int bitCount;
  9. int bitLength;
  10. int lowestSetBit;
  11. int firstNonzeroIntNum;
  12. const static uint64_t LONG_MASK = 0xffffffffL;
  13. static const int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
  14. static const int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
  15. static const int KARATSUBA_THRESHOLD = 80;
  16. static const int TOOM_COOK_THRESHOLD = 240;
  17. static const int KARATSUBA_SQUARE_THRESHOLD = 128;
  18. static const int TOOM_COOK_SQUARE_THRESHOLD = 216;
  19. static const int BURNIKEL_ZIEGLER_THRESHOLD = 80;
  20. static const int BURNIKEL_ZIEGLER_OFFSET = 40;
  21. static const int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
  22. static const int MULTIPLY_SQUARE_THRESHOLD = 20;
  23. static const int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
  24. BigInteger(std::vector<char> val) {
  25. assert(val.size() != 0);
  26. if (val[0] < 0) {
  27. mag = makePositive(val);
  28. signum = -1;
  29. } else {
  30. mag = stripLeadingZeroBytes(val);
  31. signum = (mag.length == 0 ? 0 : 1);
  32. }
  33. if (mag.size() >= MAX_MAG_LENGTH) {
  34. checkRange();
  35. }
  36. }
  37. BigInteger(std::vector<int> val) {
  38. assert(val.size() != 0);
  39. if (val[0] < 0) {
  40. mag = makePositive(val);
  41. signum = -1;
  42. } else {
  43. mag = trustedStripLeadingZeroInts(val);
  44. signum = (mag.size() == 0 ? 0 : 1);
  45. }
  46. if (mag.size() >= MAX_MAG_LENGTH) {
  47. checkRange();
  48. }
  49. }
  50. BigInteger(int signum, std::vector<char> magnitude) {
  51. this.mag = stripLeadingZeroBytes(magnitude);
  52. assert(!(signum < -1 || signum > 1));
  53. if (this.mag.length == 0) {
  54. this.signum = 0;
  55. } else {
  56. assert(signum != 0);
  57. this.signum = signum;
  58. }
  59. if (mag.size() >= MAX_MAG_LENGTH) {
  60. checkRange();
  61. }
  62. }
  63. BigInteger(int signum, std::vector<int> magnitude) {
  64. this.mag = stripLeadingZeroInts(magnitude);
  65. assert(!(signum < -1 || signum > 1));
  66. if (this.mag.length == 0) {
  67. this.signum = 0;
  68. } else {
  69. assert(signum != 0);
  70. this.signum = signum;
  71. }
  72. if (mag.length >= MAX_MAG_LENGTH) {
  73. checkRange();
  74. }
  75. }
  76. /*
  77. * Constructs a new BigInteger using a char array with radix=10.
  78. * Sign is precalculated outside and not allowed in the val.
  79. */
  80. BigInteger(std::vector<char> val, int sign, int len) {
  81. int cursor = 0, numDigits;
  82. // Skip leading zeros and compute number of digits in magnitude
  83. while (cursor < len && Character.digit(val[cursor], 10) == 0) {
  84. cursor++;
  85. }
  86. if (cursor == len) {
  87. signum = 0;
  88. mag = ZERO.mag;
  89. return;
  90. }
  91. numDigits = len - cursor;
  92. signum = sign;
  93. // Pre-allocate array of expected size
  94. unsigned int numWords;
  95. if (len < 10) {
  96. numWords = 1;
  97. } else {
  98. uint64_t numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;
  99. if (numBits + 31 >= (1L << 32)) {
  100. reportOverflow();
  101. }
  102. numWords = (int) (numBits + 31) >>> 5;
  103. }
  104. std::vector<int> magnitude(numBits);
  105. // Process first (potentially short) digit group
  106. int firstGroupLen = numDigits % digitsPerInt[10];
  107. if (firstGroupLen == 0)
  108. firstGroupLen = digitsPerInt[10];
  109. magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen);
  110. // Process remaining digit groups
  111. while (cursor < len) {
  112. int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
  113. destructiveMulAdd(magnitude, intRadix[10], groupVal);
  114. }
  115. mag = trustedStripLeadingZeroInts(magnitude);
  116. if (mag.length >= MAX_MAG_LENGTH) {
  117. checkRange();
  118. }
  119. }
  120. int digit(char a){
  121. assert((int)(a - '0') < 10 && (int)(a - '0') >= 0);
  122. return (int)(a - '0');
  123. }
  124. // Create an integer with the digits between the two indexes
  125. // Assumes start < end. The result may be negative, but it
  126. // is to be treated as an unsigned value.
  127. int parseInt(const std::vector<char>& source, int start, int end) {
  128. int result = digit(source[start++]);
  129. for (int index = start; index < end; index++) {
  130. int nextVal = digit(source[index]);
  131. result = 10 * result + nextVal;
  132. }
  133. return result;
  134. }
  135. // bitsPerDigit in the given radix times 1024
  136. // Rounded up to avoid underallocation.
  137. static uint64_t bitsPerDigit[] = { 0, 0,
  138. 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
  139. 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
  140. 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
  141. 5253, 5295};
  142. // Multiply x array times word y in place, and add word z
  143. static void destructiveMulAdd(std::vector<int>& x, int y, int z) {
  144. // Perform the multiplication word by word
  145. uint64_t ylong = y & LONG_MASK;
  146. uint64_t zlong = z & LONG_MASK;
  147. int len = x.length;
  148. uint64_t product = 0;
  149. uint64_t carry = 0;
  150. for (int i = len-1; i >= 0; i--) {
  151. product = ylong * (x[i] & LONG_MASK) + carry;
  152. x[i] = (int)product;
  153. carry = product >>> 32;
  154. }
  155. // Perform the addition
  156. uint64_t sum = (x[len-1] & LONG_MASK) + zlong;
  157. x[len-1] = (int)sum;
  158. carry = sum >> 32;
  159. for (int i = len-2; i >= 0; i--) {
  160. sum = (x[i] & LONG_MASK) + carry;
  161. x[i] = (int)sum;
  162. carry = sum >> 32;
  163. }
  164. }
  165. BigInteger(std::string val) : BigInteger(val, 10) {
  166. }
  167. BigInteger(int numBits, std::mt19937_64& rnd) : BigInteger(1, randomBits(numBits, rnd)) {
  168. }
  169. static std::vector<char> randomBits(unsigned int numBits, std::mt19937_64& rnd) {
  170. unsigned int numBytes = (unsigned int)(((uint64_t)numBits+7)/8); // avoid overflow
  171. std::vector<char> randomBits(numBytes);
  172. std::uniform_int_distribution<char> dis(-128,127);
  173. // Generate random bytes and mask out any excess bits
  174. if (numBytes > 0) {
  175. std::generate(randomBits.begin(), randomBits.end(), [&](){return dis(rnd)});
  176. int excessBits = 8*numBytes - numBits;
  177. randomBits[0] &= (1 << (8-excessBits)) - 1;
  178. }
  179. return randomBits;
  180. }
  181. BigInteger(int bitLength, int certainty, std::mt19937_64& rnd) {
  182. BigInteger prime;
  183. assert(bitLength >= 2);
  184. prime = (bitLength < SMALL_PRIME_THRESHOLD
  185. ? smallPrime(bitLength, certainty, rnd)
  186. : largePrime(bitLength, certainty, rnd));
  187. signum = 1;
  188. mag = prime.mag;
  189. }
  190. // Minimum size in bits that the requested prime number has
  191. // before we use the large prime number generating algorithms.
  192. // The cutoff of 95 was chosen empirically for best performance.
  193. static const int SMALL_PRIME_THRESHOLD = 95;
  194. // Certainty required to meet the spec of probablePrime
  195. static const int DEFAULT_PRIME_CERTAINTY = 100;
  196. /*static BigInteger probablePrime(int bitLength, Random rnd) {
  197. if (bitLength < 2)
  198. throw new ArithmeticException("bitLength < 2");
  199. return (bitLength < SMALL_PRIME_THRESHOLD ?
  200. smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
  201. largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
  202. }
  203. static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
  204. int magLen = (bitLength + 31) >>> 5;
  205. int temp[] = new int[magLen];
  206. int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int
  207. int highMask = (highBit << 1) - 1; // Bits to keep in high int
  208. while (true) {
  209. // Construct a candidate
  210. for (int i=0; i < magLen; i++)
  211. temp[i] = rnd.nextInt();
  212. temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length
  213. if (bitLength > 2)
  214. temp[magLen-1] |= 1; // Make odd if bitlen > 2
  215. BigInteger p = new BigInteger(temp, 1);
  216. // Do cheap "pre-test" if applicable
  217. if (bitLength > 6) {
  218. long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
  219. if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
  220. (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
  221. (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
  222. continue; // Candidate is composite; try another
  223. }
  224. // All candidates of bitLength 2 and 3 are prime by this point
  225. if (bitLength < 4)
  226. return p;
  227. // Do expensive test if we survive pre-test (or it's inapplicable)
  228. if (p.primeToCertainty(certainty, rnd))
  229. return p;
  230. }
  231. }
  232. static const BigInteger SMALL_PRIME_PRODUCT
  233. = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
  234. static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
  235. BigInteger p;
  236. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  237. p.mag[p.mag.length-1] &= 0xfffffffe;
  238. // Use a sieve length likely to contain the next prime number
  239. int searchLen = getPrimeSearchLen(bitLength);
  240. BitSieve searchSieve = new BitSieve(p, searchLen);
  241. BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
  242. while ((candidate == null) || (candidate.bitLength() != bitLength)) {
  243. p = p.add(BigInteger.valueOf(2*searchLen));
  244. if (p.bitLength() != bitLength)
  245. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  246. p.mag[p.mag.length-1] &= 0xfffffffe;
  247. searchSieve = new BitSieve(p, searchLen);
  248. candidate = searchSieve.retrieve(p, certainty, rnd);
  249. }
  250. return candidate;
  251. }
  252. BigInteger nextProbablePrime() {
  253. if (this.signum < 0)
  254. throw new ArithmeticException("start < 0: " + this);
  255. // Handle trivial cases
  256. if ((this.signum == 0) || this.equals(ONE))
  257. return TWO;
  258. BigInteger result = this.add(ONE);
  259. // Fastpath for small numbers
  260. if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
  261. // Ensure an odd number
  262. if (!result.testBit(0))
  263. result = result.add(ONE);
  264. while (true) {
  265. // Do cheap "pre-test" if applicable
  266. if (result.bitLength() > 6) {
  267. long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
  268. if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
  269. (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
  270. (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
  271. result = result.add(TWO);
  272. continue; // Candidate is composite; try another
  273. }
  274. }
  275. // All candidates of bitLength 2 and 3 are prime by this point
  276. if (result.bitLength() < 4)
  277. return result;
  278. // The expensive test
  279. if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
  280. return result;
  281. result = result.add(TWO);
  282. }
  283. }
  284. // Start at previous even number
  285. if (result.testBit(0))
  286. result = result.subtract(ONE);
  287. // Looking for the next large prime
  288. int searchLen = getPrimeSearchLen(result.bitLength());
  289. while (true) {
  290. BitSieve searchSieve = new BitSieve(result, searchLen);
  291. BigInteger candidate = searchSieve.retrieve(result,
  292. DEFAULT_PRIME_CERTAINTY, null);
  293. if (candidate != null)
  294. return candidate;
  295. result = result.add(BigInteger.valueOf(2 * searchLen));
  296. }
  297. }
  298. static int getPrimeSearchLen(int bitLength) {
  299. if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {
  300. throw new ArithmeticException("Prime search implementation restriction on bitLength");
  301. }
  302. return bitLength / 20 * 64;
  303. }*/
  304. bool primeToCertainty(int certainty, std::mt19937_64& random) {
  305. int rounds = 0;
  306. int n = (std::min(certainty, Integer.MAX_VALUE-1)+1)/2;
  307. // The relationship between the certainty and the number of rounds
  308. // we perform is given in the draft standard ANSI X9.80, "PRIME
  309. // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
  310. int sizeInBits = bitLength();
  311. if (sizeInBits < 100) {
  312. rounds = 50;
  313. rounds = n < rounds ? n : rounds;
  314. return passesMillerRabin(rounds, random);
  315. }
  316. if (sizeInBits < 256) {
  317. rounds = 27;
  318. } else if (sizeInBits < 512) {
  319. rounds = 15;
  320. } else if (sizeInBits < 768) {
  321. rounds = 8;
  322. } else if (sizeInBits < 1024) {
  323. rounds = 4;
  324. } else {
  325. rounds = 2;
  326. }
  327. rounds = n < rounds ? n : rounds;
  328. return passesMillerRabin(rounds, random) && passesLucasLehmer();
  329. }
  330. boolean passesLucasLehmer() {
  331. BigInteger thisPlusOne = this.add(ONE);
  332. // Step 1
  333. int d = 5;
  334. while (jacobiSymbol(d, this) != -1) {
  335. // 5, -7, 9, -11, ...
  336. d = (d < 0) ? Math.abs(d)+2 : -(d+2);
  337. }
  338. // Step 2
  339. BigInteger u = lucasLehmerSequence(d, thisPlusOne, this);
  340. // Step 3
  341. return u.mod(this).equals(ZERO);
  342. }
  343. static int jacobiSymbol(int p, BigInteger n) {
  344. if (p == 0)
  345. return 0;
  346. // Algorithm and comments adapted from Colin Plumb's C library.
  347. int j = 1;
  348. int u = n.mag[n.mag.length-1];
  349. // Make p positive
  350. if (p < 0) {
  351. p = -p;
  352. int n8 = u & 7;
  353. if ((n8 == 3) || (n8 == 7))
  354. j = -j; // 3 (011) or 7 (111) mod 8
  355. }
  356. // Get rid of factors of 2 in p
  357. while ((p & 3) == 0)
  358. p >>= 2;
  359. if ((p & 1) == 0) {
  360. p >>= 1;
  361. if (((u ^ (u>>1)) & 2) != 0)
  362. j = -j; // 3 (011) or 5 (101) mod 8
  363. }
  364. if (p == 1)
  365. return j;
  366. // Then, apply quadratic reciprocity
  367. if ((p & u & 2) != 0) // p = u = 3 (mod 4)?
  368. j = -j;
  369. // And reduce u mod p
  370. u = n.mod(BigInteger.valueOf(p)).intValue();
  371. // Now compute Jacobi(u,p), u < p
  372. while (u != 0) {
  373. while ((u & 3) == 0)
  374. u >>= 2;
  375. if ((u & 1) == 0) {
  376. u >>= 1;
  377. if (((p ^ (p>>1)) & 2) != 0)
  378. j = -j; // 3 (011) or 5 (101) mod 8
  379. }
  380. if (u == 1)
  381. return j;
  382. // Now both u and p are odd, so use quadratic reciprocity
  383. assert (u < p);
  384. int t = u; u = p; p = t;
  385. if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
  386. j = -j;
  387. // Now u >= p, so it can be reduced
  388. u %= p;
  389. }
  390. return 0;
  391. }
  392. static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
  393. BigInteger d = BigInteger.valueOf(z);
  394. BigInteger u = ONE; BigInteger u2;
  395. BigInteger v = ONE; BigInteger v2;
  396. for (int i=k.bitLength()-2; i >= 0; i--) {
  397. u2 = u.multiply(v).mod(n);
  398. v2 = v.square().add(d.multiply(u.square())).mod(n);
  399. if (v2.testBit(0))
  400. v2 = v2.subtract(n);
  401. v2 = v2.shiftRight(1);
  402. u = u2; v = v2;
  403. if (k.testBit(i)) {
  404. u2 = u.add(v).mod(n);
  405. if (u2.testBit(0))
  406. u2 = u2.subtract(n);
  407. u2 = u2.shiftRight(1);
  408. v2 = v.add(d.multiply(u)).mod(n);
  409. if (v2.testBit(0))
  410. v2 = v2.subtract(n);
  411. v2 = v2.shiftRight(1);
  412. u = u2; v = v2;
  413. }
  414. }
  415. return u;
  416. }
  417. bool passesMillerRabin(int iterations, std::mt19937_64& rnd) {
  418. // Find a and m such that m is odd and this == 1 + 2**a * m
  419. BigInteger thisMinusOne = this->subtract(ONE);
  420. BigInteger m = thisMinusOne;
  421. int a = m.getLowestSetBit();
  422. m = m.shiftRight(a);
  423. // Do the tests
  424. if (rnd == null) {
  425. rnd = ThreadLocalRandom.current();
  426. }
  427. for (int i=0; i < iterations; i++) {
  428. // Generate a uniform random on (1, this)
  429. BigInteger b;
  430. do {
  431. b = new BigInteger(this.bitLength(), rnd);
  432. } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0);
  433. int j = 0;
  434. BigInteger z = b.modPow(m, this);
  435. while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
  436. if (j > 0 && z.equals(ONE) || ++j == a)
  437. return false;
  438. z = z.modPow(TWO, this);
  439. }
  440. }
  441. return true;
  442. }
  443. BigInteger(int[] magnitude, int signum) {
  444. this.signum = (magnitude.length == 0 ? 0 : signum);
  445. this.mag = magnitude;
  446. if (mag.length >= MAX_MAG_LENGTH) {
  447. checkRange();
  448. }
  449. }
  450. BigInteger(byte[] magnitude, int signum) {
  451. this.signum = (magnitude.length == 0 ? 0 : signum);
  452. this.mag = stripLeadingZeroBytes(magnitude);
  453. if (mag.length >= MAX_MAG_LENGTH) {
  454. checkRange();
  455. }
  456. }
  457. void checkRange() {
  458. if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
  459. reportOverflow();
  460. }
  461. }
  462. static void reportOverflow() {
  463. throw new ArithmeticException("BigInteger would overflow supported range");
  464. }
  465. //Static Factory Methods
  466. static BigInteger valueOf(long val) {
  467. // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
  468. if (val == 0)
  469. return ZERO;
  470. if (val > 0 && val <= MAX_CONSTANT)
  471. return posConst[(int) val];
  472. else if (val < 0 && val >= -MAX_CONSTANT)
  473. return negConst[(int) -val];
  474. return new BigInteger(val);
  475. }
  476. BigInteger(long val) {
  477. if (val < 0) {
  478. val = -val;
  479. signum = -1;
  480. } else {
  481. signum = 1;
  482. }
  483. int highWord = (int)(val >>> 32);
  484. if (highWord == 0) {
  485. mag = new int[1];
  486. mag[0] = (int)val;
  487. } else {
  488. mag = new int[2];
  489. mag[0] = highWord;
  490. mag[1] = (int)val;
  491. }
  492. }
  493. static BigInteger valueOf(int val[]) {
  494. return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val));
  495. }
  496. // Constants
  497. const static int MAX_CONSTANT = 16;
  498. static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
  499. static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
  500. static volatile BigInteger[][] powerCache;
  501. static const double[] logCache;
  502. static const double LOG_TWO = Math.log(2.0);
  503. static {
  504. for (int i = 1; i <= MAX_CONSTANT; i++) {
  505. int[] magnitude = new int[1];
  506. magnitude[0] = i;
  507. posConst[i] = new BigInteger(magnitude, 1);
  508. negConst[i] = new BigInteger(magnitude, -1);
  509. }
  510. /*
  511. * Initialize the cache of radix^(2^x) values used for base conversion
  512. * with just the very first value. Additional values will be created
  513. * on demand.
  514. */
  515. powerCache = new BigInteger[Character.MAX_RADIX+1][];
  516. logCache = new double[Character.MAX_RADIX+1];
  517. for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
  518. powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };
  519. logCache[i] = Math.log(i);
  520. }
  521. }
  522. static const BigInteger ZERO = new BigInteger(new int[0], 0);
  523. static const BigInteger ONE = valueOf(1);
  524. static const BigInteger TWO = valueOf(2);
  525. static const BigInteger NEGATIVE_ONE = valueOf(-1);
  526. static const BigInteger TEN = valueOf(10);
  527. // Arithmetic Operations
  528. BigInteger add(BigInteger val) {
  529. if (val.signum == 0)
  530. return this;
  531. if (signum == 0)
  532. return val;
  533. if (val.signum == signum)
  534. return new BigInteger(add(mag, val.mag), signum);
  535. int cmp = compareMagnitude(val);
  536. if (cmp == 0)
  537. return ZERO;
  538. int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
  539. : subtract(val.mag, mag));
  540. resultMag = trustedStripLeadingZeroInts(resultMag);
  541. return new BigInteger(resultMag, cmp == signum ? 1 : -1);
  542. }
  543. BigInteger add(long val) {
  544. if (val == 0)
  545. return this;
  546. if (signum == 0)
  547. return valueOf(val);
  548. if (Long.signum(val) == signum)
  549. return new BigInteger(add(mag, Math.abs(val)), signum);
  550. int cmp = compareMagnitude(val);
  551. if (cmp == 0)
  552. return ZERO;
  553. int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));
  554. resultMag = trustedStripLeadingZeroInts(resultMag);
  555. return new BigInteger(resultMag, cmp == signum ? 1 : -1);
  556. }
  557. static int[] add(int[] x, long val) {
  558. int[] y;
  559. long sum = 0;
  560. int xIndex = x.length;
  561. int[] result;
  562. int highWord = (int)(val >>> 32);
  563. if (highWord == 0) {
  564. result = new int[xIndex];
  565. sum = (x[--xIndex] & LONG_MASK) + val;
  566. result[xIndex] = (int)sum;
  567. } else {
  568. if (xIndex == 1) {
  569. result = new int[2];
  570. sum = val + (x[0] & LONG_MASK);
  571. result[1] = (int)sum;
  572. result[0] = (int)(sum >>> 32);
  573. return result;
  574. } else {
  575. result = new int[xIndex];
  576. sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);
  577. result[xIndex] = (int)sum;
  578. sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);
  579. result[xIndex] = (int)sum;
  580. }
  581. }
  582. // Copy remainder of longer number while carry propagation is required
  583. bool carry = (sum >>> 32 != 0);
  584. while (xIndex > 0 && carry)
  585. carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
  586. // Copy remainder of longer number
  587. while (xIndex > 0)
  588. result[--xIndex] = x[xIndex];
  589. // Grow result if necessary
  590. if (carry) {
  591. int bigger[] = new int[result.length + 1];
  592. System.arraycopy(result, 0, bigger, 1, result.length);
  593. bigger[0] = 0x01;
  594. return bigger;
  595. }
  596. return result;
  597. }
  598. static int[] add(int[] x, int[] y) {
  599. // If x is shorter, swap the two arrays
  600. if (x.length < y.length) {
  601. int[] tmp = x;
  602. x = y;
  603. y = tmp;
  604. }
  605. int xIndex = x.length;
  606. int yIndex = y.length;
  607. int result[] = new int[xIndex];
  608. long sum = 0;
  609. if (yIndex == 1) {
  610. sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
  611. result[xIndex] = (int)sum;
  612. } else {
  613. // Add common parts of both numbers
  614. while (yIndex > 0) {
  615. sum = (x[--xIndex] & LONG_MASK) +
  616. (y[--yIndex] & LONG_MASK) + (sum >>> 32);
  617. result[xIndex] = (int)sum;
  618. }
  619. }
  620. // Copy remainder of longer number while carry propagation is required
  621. boolean carry = (sum >>> 32 != 0);
  622. while (xIndex > 0 && carry)
  623. carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
  624. // Copy remainder of longer number
  625. while (xIndex > 0)
  626. result[--xIndex] = x[xIndex];
  627. // Grow result if necessary
  628. if (carry) {
  629. int bigger[] = new int[result.length + 1];
  630. System.arraycopy(result, 0, bigger, 1, result.length);
  631. bigger[0] = 0x01;
  632. return bigger;
  633. }
  634. return result;
  635. }
  636. static int[] subtract(long val, int[] little) {
  637. int highWord = (int)(val >>> 32);
  638. if (highWord == 0) {
  639. int result[] = new int[1];
  640. result[0] = (int)(val - (little[0] & LONG_MASK));
  641. return result;
  642. } else {
  643. int result[] = new int[2];
  644. if (little.length == 1) {
  645. long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);
  646. result[1] = (int)difference;
  647. // Subtract remainder of longer number while borrow propagates
  648. boolean borrow = (difference >> 32 != 0);
  649. if (borrow) {
  650. result[0] = highWord - 1;
  651. } else { // Copy remainder of longer number
  652. result[0] = highWord;
  653. }
  654. return result;
  655. } else { // little.length == 2
  656. long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);
  657. result[1] = (int)difference;
  658. difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);
  659. result[0] = (int)difference;
  660. return result;
  661. }
  662. }
  663. }
  664. static int[] subtract(int[] big, long val) {
  665. int highWord = (int)(val >>> 32);
  666. int bigIndex = big.length;
  667. int result[] = new int[bigIndex];
  668. long difference = 0;
  669. if (highWord == 0) {
  670. difference = (big[--bigIndex] & LONG_MASK) - val;
  671. result[bigIndex] = (int)difference;
  672. } else {
  673. difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);
  674. result[bigIndex] = (int)difference;
  675. difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);
  676. result[bigIndex] = (int)difference;
  677. }
  678. // Subtract remainder of longer number while borrow propagates
  679. boolean borrow = (difference >> 32 != 0);
  680. while (bigIndex > 0 && borrow)
  681. borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
  682. // Copy remainder of longer number
  683. while (bigIndex > 0)
  684. result[--bigIndex] = big[bigIndex];
  685. return result;
  686. }
  687. BigInteger subtract(BigInteger val) {
  688. if (val.signum == 0)
  689. return this;
  690. if (signum == 0)
  691. return val.negate();
  692. if (val.signum != signum)
  693. return new BigInteger(add(mag, val.mag), signum);
  694. int cmp = compareMagnitude(val);
  695. if (cmp == 0)
  696. return ZERO;
  697. int[] resultMag = (cmp > 0 ? subtract(mag, val.mag)
  698. : subtract(val.mag, mag));
  699. resultMag = trustedStripLeadingZeroInts(resultMag);
  700. return new BigInteger(resultMag, cmp == signum ? 1 : -1);
  701. }
  702. static int[] subtract(int[] big, int[] little) {
  703. int bigIndex = big.length;
  704. int result[] = new int[bigIndex];
  705. int littleIndex = little.length;
  706. long difference = 0;
  707. // Subtract common parts of both numbers
  708. while (littleIndex > 0) {
  709. difference = (big[--bigIndex] & LONG_MASK) -
  710. (little[--littleIndex] & LONG_MASK) +
  711. (difference >> 32);
  712. result[bigIndex] = (int)difference;
  713. }
  714. // Subtract remainder of longer number while borrow propagates
  715. boolean borrow = (difference >> 32 != 0);
  716. while (bigIndex > 0 && borrow)
  717. borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
  718. // Copy remainder of longer number
  719. while (bigIndex > 0)
  720. result[--bigIndex] = big[bigIndex];
  721. return result;
  722. }
  723. BigInteger multiply(BigInteger val) {
  724. if (val.signum == 0 || signum == 0)
  725. return ZERO;
  726. int xlen = mag.length;
  727. if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) {
  728. return square();
  729. }
  730. int ylen = val.mag.length;
  731. if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) {
  732. int resultSign = signum == val.signum ? 1 : -1;
  733. if (val.mag.length == 1) {
  734. return multiplyByInt(mag,val.mag[0], resultSign);
  735. }
  736. if (mag.length == 1) {
  737. return multiplyByInt(val.mag,mag[0], resultSign);
  738. }
  739. int[] result = multiplyToLen(mag, xlen,
  740. val.mag, ylen, null);
  741. result = trustedStripLeadingZeroInts(result);
  742. return new BigInteger(result, resultSign);
  743. } else {
  744. if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
  745. return multiplyKaratsuba(this, val);
  746. } else {
  747. return multiplyToomCook3(this, val);
  748. }
  749. }
  750. }
  751. static BigInteger multiplyByInt(int[] x, int y, int sign) {
  752. if (Integer.bitCount(y) == 1) {
  753. return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign);
  754. }
  755. int xlen = x.length;
  756. int[] rmag = new int[xlen + 1];
  757. long carry = 0;
  758. long yl = y & LONG_MASK;
  759. int rstart = rmag.length - 1;
  760. for (int i = xlen - 1; i >= 0; i--) {
  761. long product = (x[i] & LONG_MASK) * yl + carry;
  762. rmag[rstart--] = (int)product;
  763. carry = product >>> 32;
  764. }
  765. if (carry == 0L) {
  766. rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
  767. } else {
  768. rmag[rstart] = (int)carry;
  769. }
  770. return new BigInteger(rmag, sign);
  771. }
  772. BigInteger multiply(long v) {
  773. if (v == 0 || signum == 0)
  774. return ZERO;
  775. if (v == Long.MIN_VALUE)
  776. return multiply(BigInteger.valueOf(v));
  777. int rsign = (v > 0 ? signum : -signum);
  778. if (v < 0)
  779. v = -v;
  780. long dh = v >>> 32; // higher order bits
  781. long dl = v & LONG_MASK; // lower order bits
  782. int xlen = mag.length;
  783. int[] value = mag;
  784. int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]);
  785. long carry = 0;
  786. int rstart = rmag.length - 1;
  787. for (int i = xlen - 1; i >= 0; i--) {
  788. long product = (value[i] & LONG_MASK) * dl + carry;
  789. rmag[rstart--] = (int)product;
  790. carry = product >>> 32;
  791. }
  792. rmag[rstart] = (int)carry;
  793. if (dh != 0L) {
  794. carry = 0;
  795. rstart = rmag.length - 2;
  796. for (int i = xlen - 1; i >= 0; i--) {
  797. long product = (value[i] & LONG_MASK) * dh +
  798. (rmag[rstart] & LONG_MASK) + carry;
  799. rmag[rstart--] = (int)product;
  800. carry = product >>> 32;
  801. }
  802. rmag[0] = (int)carry;
  803. }
  804. if (carry == 0L)
  805. rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length);
  806. return new BigInteger(rmag, rsign);
  807. }
  808. static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) {
  809. int xstart = xlen - 1;
  810. int ystart = ylen - 1;
  811. if (z == null || z.length < (xlen+ ylen))
  812. z = new int[xlen+ylen];
  813. long carry = 0;
  814. for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
  815. long product = (y[j] & LONG_MASK) *
  816. (x[xstart] & LONG_MASK) + carry;
  817. z[k] = (int)product;
  818. carry = product >>> 32;
  819. }
  820. z[xstart] = (int)carry;
  821. for (int i = xstart-1; i >= 0; i--) {
  822. carry = 0;
  823. for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {
  824. long product = (y[j] & LONG_MASK) *
  825. (x[i] & LONG_MASK) +
  826. (z[k] & LONG_MASK) + carry;
  827. z[k] = (int)product;
  828. carry = product >>> 32;
  829. }
  830. z[i] = (int)carry;
  831. }
  832. return z;
  833. }
  834. static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
  835. int xlen = x.mag.length;
  836. int ylen = y.mag.length;
  837. // The number of ints in each half of the number.
  838. int half = (Math.max(xlen, ylen)+1) / 2;
  839. // xl and yl are the lower halves of x and y respectively,
  840. // xh and yh are the upper halves.
  841. BigInteger xl = x.getLower(half);
  842. BigInteger xh = x.getUpper(half);
  843. BigInteger yl = y.getLower(half);
  844. BigInteger yh = y.getUpper(half);
  845. BigInteger p1 = xh.multiply(yh); // p1 = xh*yh
  846. BigInteger p2 = xl.multiply(yl); // p2 = xl*yl
  847. // p3=(xh+xl)*(yh+yl)
  848. BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
  849. // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
  850. BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
  851. if (x.signum != y.signum) {
  852. return result.negate();
  853. } else {
  854. return result;
  855. }
  856. }
  857. static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
  858. int alen = a.mag.length;
  859. int blen = b.mag.length;
  860. int largest = std::max(alen, blen);
  861. // k is the size (in ints) of the lower-order slices.
  862. int k = (largest+2)/3; // Equal to ceil(largest/3)
  863. // r is the size (in ints) of the highest-order slice.
  864. int r = largest - 2*k;
  865. // Obtain slices of the numbers. a2 and b2 are the most significant
  866. // bits of the numbers a and b, and a0 and b0 the least significant.
  867. BigInteger a0, a1, a2, b0, b1, b2;
  868. a2 = a.getToomSlice(k, r, 0, largest);
  869. a1 = a.getToomSlice(k, r, 1, largest);
  870. a0 = a.getToomSlice(k, r, 2, largest);
  871. b2 = b.getToomSlice(k, r, 0, largest);
  872. b1 = b.getToomSlice(k, r, 1, largest);
  873. b0 = b.getToomSlice(k, r, 2, largest);
  874. BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
  875. v0 = a0.multiply(b0);
  876. da1 = a2.add(a0);
  877. db1 = b2.add(b0);
  878. vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
  879. da1 = da1.add(a1);
  880. db1 = db1.add(b1);
  881. v1 = da1.multiply(db1);
  882. v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
  883. db1.add(b2).shiftLeft(1).subtract(b0));
  884. vinf = a2.multiply(b2);
  885. // The algorithm requires two divisions by 2 and one by 3.
  886. // All divisions are known to be exact, that is, they do not produce
  887. // remainders, and all results are positive. The divisions by 2 are
  888. // implemented as right shifts which are relatively efficient, leaving
  889. // only an exact division by 3, which is done by a specialized
  890. // linear-time algorithm.
  891. t2 = v2.subtract(vm1).exactDivideBy3();
  892. tm1 = v1.subtract(vm1).shiftRight(1);
  893. t1 = v1.subtract(v0);
  894. t2 = t2.subtract(t1).shiftRight(1);
  895. t1 = t1.subtract(tm1).subtract(vinf);
  896. t2 = t2.subtract(vinf.shiftLeft(1));
  897. tm1 = tm1.subtract(t2);
  898. // Number of bits to shift left.
  899. int ss = k*32;
  900. BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
  901. if (a.signum != b.signum) {
  902. return result.negate();
  903. } else {
  904. return result;
  905. }
  906. }
  907. BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
  908. int fullsize) {
  909. int start, end, sliceSize, len, offset;
  910. len = mag.length;
  911. offset = fullsize - len;
  912. if (slice == 0) {
  913. start = 0 - offset;
  914. end = upperSize - 1 - offset;
  915. } else {
  916. start = upperSize + (slice-1)*lowerSize - offset;
  917. end = start + lowerSize - 1;
  918. }
  919. if (start < 0) {
  920. start = 0;
  921. }
  922. if (end < 0) {
  923. return ZERO;
  924. }
  925. sliceSize = (end-start) + 1;
  926. if (sliceSize <= 0) {
  927. return ZERO;
  928. }
  929. // While performing Toom-Cook, all slices are positive and
  930. // the sign is adjusted when the const number is composed.
  931. if (start == 0 && sliceSize >= len) {
  932. return this.abs();
  933. }
  934. int intSlice[] = new int[sliceSize];
  935. System.arraycopy(mag, start, intSlice, 0, sliceSize);
  936. return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
  937. }
  938. BigInteger exactDivideBy3() {
  939. int len = mag.length;
  940. int[] result = new int[len];
  941. long x, w, q, borrow;
  942. borrow = 0L;
  943. for (int i=len-1; i >= 0; i--) {
  944. x = (mag[i] & LONG_MASK);
  945. w = x - borrow;
  946. if (borrow > x) { // Did we make the number go negative?
  947. borrow = 1L;
  948. } else {
  949. borrow = 0L;
  950. }
  951. // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus,
  952. // the effect of this is to divide by 3 (mod 2^32).
  953. // This is much faster than division on most architectures.
  954. q = (w * 0xAAAAAAABL) & LONG_MASK;
  955. result[i] = (int) q;
  956. // Now check the borrow. The second check can of course be
  957. // eliminated if the first fails.
  958. if (q >= 0x55555556L) {
  959. borrow++;
  960. if (q >= 0xAAAAAAABL)
  961. borrow++;
  962. }
  963. }
  964. result = trustedStripLeadingZeroInts(result);
  965. return new BigInteger(result, signum);
  966. }
  967. BigInteger getLower(int n) {
  968. int len = mag.length;
  969. if (len <= n) {
  970. return abs();
  971. }
  972. int lowerInts[] = new int[n];
  973. System.arraycopy(mag, len-n, lowerInts, 0, n);
  974. return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
  975. }
  976. BigInteger getUpper(int n) {
  977. int len = mag.length;
  978. if (len <= n) {
  979. return ZERO;
  980. }
  981. int upperLen = len - n;
  982. int upperInts[] = new int[upperLen];
  983. System.arraycopy(mag, 0, upperInts, 0, upperLen);
  984. return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
  985. }
  986. // Squaring
  987. BigInteger square() {
  988. if (signum == 0) {
  989. return ZERO;
  990. }
  991. int len = mag.length;
  992. if (len < KARATSUBA_SQUARE_THRESHOLD) {
  993. int[] z = squareToLen(mag, len, null);
  994. return new BigInteger(trustedStripLeadingZeroInts(z), 1);
  995. } else {
  996. if (len < TOOM_COOK_SQUARE_THRESHOLD) {
  997. return squareKaratsuba();
  998. } else {
  999. return squareToomCook3();
  1000. }
  1001. }
  1002. }
  1003. static const int[] squareToLen(int[] x, int len, int[] z) {
  1004. int zlen = len << 1;
  1005. if (z == null || z.length < zlen)
  1006. z = new int[zlen];
  1007. // Execute checks before calling intrinsified method.
  1008. implSquareToLenChecks(x, len, z, zlen);
  1009. return implSquareToLen(x, len, z, zlen);
  1010. }
  1011. static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException {
  1012. if (len < 1) {
  1013. throw new IllegalArgumentException("invalid input length: " + len);
  1014. }
  1015. if (len > x.length) {
  1016. throw new IllegalArgumentException("input length out of bound: " +
  1017. len + " > " + x.length);
  1018. }
  1019. if (len * 2 > z.length) {
  1020. throw new IllegalArgumentException("input length out of bound: " +
  1021. (len * 2) + " > " + z.length);
  1022. }
  1023. if (zlen < 1) {
  1024. throw new IllegalArgumentException("invalid input length: " + zlen);
  1025. }
  1026. if (zlen > z.length) {
  1027. throw new IllegalArgumentException("input length out of bound: " +
  1028. len + " > " + z.length);
  1029. }
  1030. }
  1031. static const int[] implSquareToLen(int[] x, int len, int[] z, int zlen) {
  1032. /*
  1033. * The algorithm used here is adapted from Colin Plumb's C library.
  1034. * Technique: Consider the partial products in the multiplication
  1035. * of "abcde" by itself:
  1036. *
  1037. * a b c d e
  1038. * * a b c d e
  1039. * ==================
  1040. * ae be ce de ee
  1041. * ad bd cd dd de
  1042. * ac bc cc cd ce
  1043. * ab bb bc bd be
  1044. * aa ab ac ad ae
  1045. *
  1046. * Note that everything above the main diagonal:
  1047. * ae be ce de = (abcd) * e
  1048. * ad bd cd = (abc) * d
  1049. * ac bc = (ab) * c
  1050. * ab = (a) * b
  1051. *
  1052. * is a copy of everything below the main diagonal:
  1053. * de
  1054. * cd ce
  1055. * bc bd be
  1056. * ab ac ad ae
  1057. *
  1058. * Thus, the sum is 2 * (off the diagonal) + diagonal.
  1059. *
  1060. * This is accumulated beginning with the diagonal (which
  1061. * consist of the squares of the digits of the input), which is then
  1062. * divided by two, the off-diagonal added, and multiplied by two
  1063. * again. The low bit is simply a copy of the low bit of the
  1064. * input, so it doesn't need special care.
  1065. */
  1066. // Store the squares, right shifted one bit (i.e., divided by 2)
  1067. int lastProductLowWord = 0;
  1068. for (int j=0, i=0; j < len; j++) {
  1069. long piece = (x[j] & LONG_MASK);
  1070. long product = piece * piece;
  1071. z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33);
  1072. z[i++] = (int)(product >>> 1);
  1073. lastProductLowWord = (int)product;
  1074. }
  1075. // Add in off-diagonal sums
  1076. for (int i=len, offset=1; i > 0; i--, offset+=2) {
  1077. int t = x[i-1];
  1078. t = mulAdd(z, x, offset, i-1, t);
  1079. addOne(z, offset-1, i, t);
  1080. }
  1081. // Shift back up and set low bit
  1082. primitiveLeftShift(z, zlen, 1);
  1083. z[zlen-1] |= x[len-1] & 1;
  1084. return z;
  1085. }
  1086. BigInteger squareKaratsuba() {
  1087. int half = (mag.length+1) / 2;
  1088. BigInteger xl = getLower(half);
  1089. BigInteger xh = getUpper(half);
  1090. BigInteger xhs = xh.square(); // xhs = xh^2
  1091. BigInteger xls = xl.square(); // xls = xl^2
  1092. // xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
  1093. return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
  1094. }
  1095. BigInteger squareToomCook3() {
  1096. int len = mag.length;
  1097. // k is the size (in ints) of the lower-order slices.
  1098. int k = (len+2)/3; // Equal to ceil(largest/3)
  1099. // r is the size (in ints) of the highest-order slice.
  1100. int r = len - 2*k;
  1101. // Obtain slices of the numbers. a2 is the most significant
  1102. // bits of the number, and a0 the least significant.
  1103. BigInteger a0, a1, a2;
  1104. a2 = getToomSlice(k, r, 0, len);
  1105. a1 = getToomSlice(k, r, 1, len);
  1106. a0 = getToomSlice(k, r, 2, len);
  1107. BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
  1108. v0 = a0.square();
  1109. da1 = a2.add(a0);
  1110. vm1 = da1.subtract(a1).square();
  1111. da1 = da1.add(a1);
  1112. v1 = da1.square();
  1113. vinf = a2.square();
  1114. v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
  1115. // The algorithm requires two divisions by 2 and one by 3.
  1116. // All divisions are known to be exact, that is, they do not produce
  1117. // remainders, and all results are positive. The divisions by 2 are
  1118. // implemented as right shifts which are relatively efficient, leaving
  1119. // only a division by 3.
  1120. // The division by 3 is done by an optimized algorithm for this case.
  1121. t2 = v2.subtract(vm1).exactDivideBy3();
  1122. tm1 = v1.subtract(vm1).shiftRight(1);
  1123. t1 = v1.subtract(v0);
  1124. t2 = t2.subtract(t1).shiftRight(1);
  1125. t1 = t1.subtract(tm1).subtract(vinf);
  1126. t2 = t2.subtract(vinf.shiftLeft(1));
  1127. tm1 = tm1.subtract(t2);
  1128. // Number of bits to shift left.
  1129. int ss = k*32;
  1130. return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
  1131. }
  1132. // Division
  1133. BigInteger divide(BigInteger val) {
  1134. if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
  1135. mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
  1136. return divideKnuth(val);
  1137. } else {
  1138. return divideBurnikelZiegler(val);
  1139. }
  1140. }
  1141. BigInteger divideKnuth(BigInteger val) {
  1142. MutableBigInteger q = new MutableBigInteger(),
  1143. a = new MutableBigInteger(this.mag),
  1144. b = new MutableBigInteger(val.mag);
  1145. a.divideKnuth(b, q, false);
  1146. return q.toBigInteger(this.signum * val.signum);
  1147. }
  1148. BigInteger[] divideAndRemainder(BigInteger val) {
  1149. if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
  1150. mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
  1151. return divideAndRemainderKnuth(val);
  1152. } else {
  1153. return divideAndRemainderBurnikelZiegler(val);
  1154. }
  1155. }
  1156. BigInteger[] divideAndRemainderKnuth(BigInteger val) {
  1157. BigInteger[] result = new BigInteger[2];
  1158. MutableBigInteger q = new MutableBigInteger(),
  1159. a = new MutableBigInteger(this.mag),
  1160. b = new MutableBigInteger(val.mag);
  1161. MutableBigInteger r = a.divideKnuth(b, q);
  1162. result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1);
  1163. result[1] = r.toBigInteger(this.signum);
  1164. return result;
  1165. }
  1166. BigInteger remainder(BigInteger val) {
  1167. if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
  1168. mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
  1169. return remainderKnuth(val);
  1170. } else {
  1171. return remainderBurnikelZiegler(val);
  1172. }
  1173. }
  1174. BigInteger remainderKnuth(BigInteger val) {
  1175. MutableBigInteger q = new MutableBigInteger(),
  1176. a = new MutableBigInteger(this.mag),
  1177. b = new MutableBigInteger(val.mag);
  1178. return a.divideKnuth(b, q).toBigInteger(this.signum);
  1179. }
  1180. BigInteger divideBurnikelZiegler(BigInteger val) {
  1181. return divideAndRemainderBurnikelZiegler(val)[0];
  1182. }
  1183. BigInteger remainderBurnikelZiegler(BigInteger val) {
  1184. return divideAndRemainderBurnikelZiegler(val)[1];
  1185. }
  1186. BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) {
  1187. MutableBigInteger q = new MutableBigInteger();
  1188. MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q);
  1189. BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);
  1190. BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);
  1191. return new BigInteger[] {qBigInt, rBigInt};
  1192. }
  1193. BigInteger pow(int exponent) {
  1194. if (exponent < 0) {
  1195. throw new ArithmeticException("Negative exponent");
  1196. }
  1197. if (signum == 0) {
  1198. return (exponent == 0 ? ONE : this);
  1199. }
  1200. BigInteger partToSquare = this.abs();
  1201. // Factor out powers of two from the base, as the exponentiation of
  1202. // these can be done by left shifts only.
  1203. // The remaining part can then be exponentiated faster. The
  1204. // powers of two will be multiplied back at the end.
  1205. int powersOfTwo = partToSquare.getLowestSetBit();
  1206. long bitsToShift = (long)powersOfTwo * exponent;
  1207. if (bitsToShift > Integer.MAX_VALUE) {
  1208. reportOverflow();
  1209. }
  1210. int remainingBits;
  1211. // Factor the powers of two out quickly by shifting right, if needed.
  1212. if (powersOfTwo > 0) {
  1213. partToSquare = partToSquare.shiftRight(powersOfTwo);
  1214. remainingBits = partToSquare.bitLength();
  1215. if (remainingBits == 1) { // Nothing left but +/- 1?
  1216. if (signum < 0 && (exponent&1) == 1) {
  1217. return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
  1218. } else {
  1219. return ONE.shiftLeft(powersOfTwo*exponent);
  1220. }
  1221. }
  1222. } else {
  1223. remainingBits = partToSquare.bitLength();
  1224. if (remainingBits == 1) { // Nothing left but +/- 1?
  1225. if (signum < 0 && (exponent&1) == 1) {
  1226. return NEGATIVE_ONE;
  1227. } else {
  1228. return ONE;
  1229. }
  1230. }
  1231. }
  1232. // This is a quick way to approximate the size of the result,
  1233. // similar to doing log2[n] * exponent. This will give an upper bound
  1234. // of how big the result can be, and which algorithm to use.
  1235. long scaleFactor = (long)remainingBits * exponent;
  1236. // Use slightly different algorithms for small and large operands.
  1237. // See if the result will safely fit into a long. (Largest 2^63-1)
  1238. if (partToSquare.mag.length == 1 && scaleFactor <= 62) {
  1239. // Small number algorithm. Everything fits into a long.
  1240. int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1);
  1241. long result = 1;
  1242. long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
  1243. int workingExponent = exponent;
  1244. // Perform exponentiation using repeated squaring trick
  1245. while (workingExponent != 0) {
  1246. if ((workingExponent & 1) == 1) {
  1247. result = result * baseToPow2;
  1248. }
  1249. if ((workingExponent >>>= 1) != 0) {
  1250. baseToPow2 = baseToPow2 * baseToPow2;
  1251. }
  1252. }
  1253. // Multiply back the powers of two (quickly, by shifting left)
  1254. if (powersOfTwo > 0) {
  1255. if (bitsToShift + scaleFactor <= 62) { // Fits in long?
  1256. return valueOf((result << bitsToShift) * newSign);
  1257. } else {
  1258. return valueOf(result*newSign).shiftLeft((int) bitsToShift);
  1259. }
  1260. }
  1261. else {
  1262. return valueOf(result*newSign);
  1263. }
  1264. } else {
  1265. // Large number algorithm. This is basically identical to
  1266. // the algorithm above, but calls multiply() and square()
  1267. // which may use more efficient algorithms for large numbers.
  1268. BigInteger answer = ONE;
  1269. int workingExponent = exponent;
  1270. // Perform exponentiation using repeated squaring trick
  1271. while (workingExponent != 0) {
  1272. if ((workingExponent & 1) == 1) {
  1273. answer = answer.multiply(partToSquare);
  1274. }
  1275. if ((workingExponent >>>= 1) != 0) {
  1276. partToSquare = partToSquare.square();
  1277. }
  1278. }
  1279. // Multiply back the (exponentiated) powers of two (quickly,
  1280. // by shifting left)
  1281. if (powersOfTwo > 0) {
  1282. answer = answer.shiftLeft(powersOfTwo*exponent);
  1283. }
  1284. if (signum < 0 && (exponent&1) == 1) {
  1285. return answer.negate();
  1286. } else {
  1287. return answer;
  1288. }
  1289. }
  1290. }
  1291. BigInteger gcd(BigInteger val) {
  1292. if (val.signum == 0)
  1293. return this.abs();
  1294. else if (this.signum == 0)
  1295. return val.abs();
  1296. MutableBigInteger a = new MutableBigInteger(this);
  1297. MutableBigInteger b = new MutableBigInteger(val);
  1298. MutableBigInteger result = a.hybridGCD(b);
  1299. return result.toBigInteger(1);
  1300. }
  1301. static int bitLengthForInt(int n) {
  1302. return 32 - Integer.numberOfLeadingZeros(n);
  1303. }
  1304. static int[] leftShift(int[] a, int len, int n) {
  1305. int nInts = n >>> 5;
  1306. int nBits = n&0x1F;
  1307. int bitsInHighWord = bitLengthForInt(a[0]);
  1308. // If shift can be done without recopy, do so
  1309. if (n <= (32-bitsInHighWord)) {
  1310. primitiveLeftShift(a, len, nBits);
  1311. return a;
  1312. } else { // Array must be resized
  1313. if (nBits <= (32-bitsInHighWord)) {
  1314. int result[] = new int[nInts+len];
  1315. System.arraycopy(a, 0, result, 0, len);
  1316. primitiveLeftShift(result, result.length, nBits);
  1317. return result;
  1318. } else {
  1319. int result[] = new int[nInts+len+1];
  1320. System.arraycopy(a, 0, result, 0, len);
  1321. primitiveRightShift(result, result.length, 32 - nBits);
  1322. return result;
  1323. }
  1324. }
  1325. }
  1326. // shifts a up to len right n bits assumes no leading zeros, 0<n<32
  1327. static void primitiveRightShift(int[] a, int len, int n) {
  1328. int n2 = 32 - n;
  1329. for (int i=len-1, c=a[i]; i > 0; i--) {
  1330. int b = c;
  1331. c = a[i-1];
  1332. a[i] = (c << n2) | (b >>> n);
  1333. }
  1334. a[0] >>>= n;
  1335. }
  1336. // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
  1337. static void primitiveLeftShift(int[] a, int len, int n) {
  1338. if (len == 0 || n == 0)
  1339. return;
  1340. int n2 = 32 - n;
  1341. for (int i=0, c=a[i], m=i+len-1; i < m; i++) {
  1342. int b = c;
  1343. c = a[i+1];
  1344. a[i] = (b << n) | (c >>> n2);
  1345. }
  1346. a[len-1] <<= n;
  1347. }
  1348. static int bitLength(int[] val, int len) {
  1349. if (len == 0)
  1350. return 0;
  1351. return ((len - 1) << 5) + bitLengthForInt(val[0]);
  1352. }
  1353. BigInteger abs() {
  1354. return (signum >= 0 ? this : this.negate());
  1355. }
  1356. BigInteger negate() {
  1357. return new BigInteger(this.mag, -this.signum);
  1358. }
  1359. int signum() {
  1360. return this.signum;
  1361. }
  1362. // Modular Arithmetic Operations
  1363. BigInteger mod(BigInteger m) {
  1364. if (m.signum <= 0)
  1365. throw new ArithmeticException("BigInteger: modulus not positive");
  1366. BigInteger result = this.remainder(m);
  1367. return (result.signum >= 0 ? result : result.add(m));
  1368. }
  1369. BigInteger modPow(BigInteger exponent, BigInteger m) {
  1370. if (m.signum <= 0)
  1371. throw new ArithmeticException("BigInteger: modulus not positive");
  1372. // Trivial cases
  1373. if (exponent.signum == 0)
  1374. return (m.equals(ONE) ? ZERO : ONE);
  1375. if (this.equals(ONE))
  1376. return (m.equals(ONE) ? ZERO : ONE);
  1377. if (this.equals(ZERO) && exponent.signum >= 0)
  1378. return ZERO;
  1379. if (this.equals(negConst[1]) && (!exponent.testBit(0)))
  1380. return (m.equals(ONE) ? ZERO : ONE);
  1381. boolean invertResult;
  1382. if ((invertResult = (exponent.signum < 0)))
  1383. exponent = exponent.negate();
  1384. BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
  1385. ? this.mod(m) : this);
  1386. BigInteger result;
  1387. if (m.testBit(0)) { // odd modulus
  1388. result = base.oddModPow(exponent, m);
  1389. } else {
  1390. /*
  1391. * Even modulus. Tear it into an "odd part" (m1) and power of two
  1392. * (m2), exponentiate mod m1, manually exponentiate mod m2, and
  1393. * use Chinese Remainder Theorem to combine results.
  1394. */
  1395. // Tear m apart into odd part (m1) and power of 2 (m2)
  1396. int p = m.getLowestSetBit(); // Max pow of 2 that divides m
  1397. BigInteger m1 = m.shiftRight(p); // m/2**p
  1398. BigInteger m2 = ONE.shiftLeft(p); // 2**p
  1399. // Calculate new base from m1
  1400. BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
  1401. ? this.mod(m1) : this);
  1402. // Caculate (base ** exponent) mod m1.
  1403. BigInteger a1 = (m1.equals(ONE) ? ZERO :
  1404. base2.oddModPow(exponent, m1));
  1405. // Calculate (this ** exponent) mod m2
  1406. BigInteger a2 = base.modPow2(exponent, p);
  1407. // Combine results using Chinese Remainder Theorem
  1408. BigInteger y1 = m2.modInverse(m1);
  1409. BigInteger y2 = m1.modInverse(m2);
  1410. if (m.mag.length < MAX_MAG_LENGTH / 2) {
  1411. result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
  1412. } else {
  1413. MutableBigInteger t1 = new MutableBigInteger();
  1414. new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1);
  1415. MutableBigInteger t2 = new MutableBigInteger();
  1416. new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2);
  1417. t1.add(t2);
  1418. MutableBigInteger q = new MutableBigInteger();
  1419. result = t1.divide(new MutableBigInteger(m), q).toBigInteger();
  1420. }
  1421. }
  1422. return (invertResult ? result.modInverse(m) : result);
  1423. }
  1424. // Montgomery multiplication. These are wrappers for
  1425. // implMontgomeryXX routines which are expected to be replaced by
  1426. // virtual machine intrinsics. We don't use the intrinsics for
  1427. // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be
  1428. // larger than any reasonable crypto key.
  1429. static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv,
  1430. int[] product) {
  1431. implMontgomeryMultiplyChecks(a, b, n, len, product);
  1432. if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
  1433. // Very long argument: do not use an intrinsic
  1434. product = multiplyToLen(a, len, b, len, product);
  1435. return montReduce(product, n, len, (int)inv);
  1436. } else {
  1437. return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));
  1438. }
  1439. }
  1440. static int[] montgomerySquare(int[] a, int[] n, int len, long inv,
  1441. int[] product) {
  1442. implMontgomeryMultiplyChecks(a, a, n, len, product);
  1443. if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
  1444. // Very long argument: do not use an intrinsic
  1445. product = squareToLen(a, len, product);
  1446. return montReduce(product, n, len, (int)inv);
  1447. } else {
  1448. return implMontgomerySquare(a, n, len, inv, materialize(product, len));
  1449. }
  1450. }
  1451. // Range-check everything.
  1452. static void implMontgomeryMultiplyChecks
  1453. (int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException {
  1454. if (len % 2 != 0) {
  1455. throw new IllegalArgumentException("input array length must be even: " + len);
  1456. }
  1457. if (len < 1) {
  1458. throw new IllegalArgumentException("invalid input length: " + len);
  1459. }
  1460. if (len > a.length ||
  1461. len > b.length ||
  1462. len > n.length ||
  1463. (product != null && len > product.length)) {
  1464. throw new IllegalArgumentException("input array length out of bound: " + len);
  1465. }
  1466. }
  1467. // Make sure that the int array z (which is expected to contain
  1468. // the result of a Montgomery multiplication) is present and
  1469. // sufficiently large.
  1470. static int[] materialize(int[] z, int len) {
  1471. if (z == null || z.length < len)
  1472. z = new int[len];
  1473. return z;
  1474. }
  1475. // These methods are intended to be be replaced by virtual machine
  1476. // intrinsics.
  1477. static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len,
  1478. long inv, int[] product) {
  1479. product = multiplyToLen(a, len, b, len, product);
  1480. return montReduce(product, n, len, (int)inv);
  1481. }
  1482. static int[] implMontgomerySquare(int[] a, int[] n, int len,
  1483. long inv, int[] product) {
  1484. product = squareToLen(a, len, product);
  1485. return montReduce(product, n, len, (int)inv);
  1486. }
  1487. static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
  1488. Integer.MAX_VALUE}; // Sentinel
  1489. BigInteger oddModPow(BigInteger y, BigInteger z) {
  1490. /*
  1491. * The algorithm is adapted from Colin Plumb's C library.
  1492. *
  1493. * The window algorithm:
  1494. * The idea is to keep a running product of b1 = n^(high-order bits of exp)
  1495. * and then keep appending exponent bits to it. The following patterns
  1496. * apply to a 3-bit window (k = 3):
  1497. * To append 0: square
  1498. * To append 1: square, multiply by n^1
  1499. * To append 10: square, multiply by n^1, square
  1500. * To append 11: square, square, multiply by n^3
  1501. * To append 100: square, multiply by n^1, square, square
  1502. * To append 101: square, square, square, multiply by n^5
  1503. * To append 110: square, square, multiply by n^3, square
  1504. * To append 111: square, square, square, multiply by n^7
  1505. *
  1506. * Since each pattern involves only one multiply, the longer the pattern
  1507. * the better, except that a 0 (no multiplies) can be appended directly.
  1508. * We precompute a table of odd powers of n, up to 2^k, and can then
  1509. * multiply k bits of exponent at a time. Actually, assuming random
  1510. * exponents, there is on average one zero bit between needs to
  1511. * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
  1512. * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
  1513. * you have to do one multiply per k+1 bits of exponent.
  1514. *
  1515. * The loop walks down the exponent, squaring the result buffer as
  1516. * it goes. There is a wbits+1 bit lookahead buffer, buf, that is
  1517. * filled with the upcoming exponent bits. (What is read after the
  1518. * end of the exponent is unimportant, but it is filled with zero here.)
  1519. * When the most-significant bit of this buffer becomes set, i.e.
  1520. * (buf & tblmask) != 0, we have to decide what pattern to multiply
  1521. * by, and when to do it. We decide, remember to do it in future
  1522. * after a suitable number of squarings have passed (e.g. a pattern
  1523. * of "100" in the buffer requires that we multiply by n^1 immediately;
  1524. * a pattern of "110" calls for multiplying by n^3 after one more
  1525. * squaring), clear the buffer, and continue.
  1526. *
  1527. * When we start, there is one more optimization: the result buffer
  1528. * is implcitly one, so squaring it or multiplying by it can be
  1529. * optimized away. Further, if we start with a pattern like "100"
  1530. * in the lookahead window, rather than placing n into the buffer
  1531. * and then starting to square it, we have already computed n^2
  1532. * to compute the odd-powers table, so we can place that into
  1533. * the buffer and save a squaring.
  1534. *
  1535. * This means that if you have a k-bit window, to compute n^z,
  1536. * where z is the high k bits of the exponent, 1/2 of the time
  1537. * it requires no squarings. 1/4 of the time, it requires 1
  1538. * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
  1539. * And the remaining 1/2^(k-1) of the time, the top k bits are a
  1540. * 1 followed by k-1 0 bits, so it again only requires k-2
  1541. * squarings, not k-1. The average of these is 1. Add that
  1542. * to the one squaring we have to do to compute the table,
  1543. * and you'll see that a k-bit window saves k-2 squarings
  1544. * as well as reducing the multiplies. (It actually doesn't
  1545. * hurt in the case k = 1, either.)
  1546. */
  1547. // Special case for exponent of one
  1548. if (y.equals(ONE))
  1549. return this;
  1550. // Special case for base of zero
  1551. if (signum == 0)
  1552. return ZERO;
  1553. int[] base = mag.clone();
  1554. int[] exp = y.mag;
  1555. int[] mod = z.mag;
  1556. int modLen = mod.length;
  1557. // Make modLen even. It is conventional to use a cryptographic
  1558. // modulus that is 512, 768, 1024, or 2048 bits, so this code
  1559. // will not normally be executed. However, it is necessary for
  1560. // the correct functioning of the HotSpot intrinsics.
  1561. if ((modLen & 1) != 0) {
  1562. int[] x = new int[modLen + 1];
  1563. System.arraycopy(mod, 0, x, 1, modLen);
  1564. mod = x;
  1565. modLen++;
  1566. }
  1567. // Select an appropriate window size
  1568. int wbits = 0;
  1569. int ebits = bitLength(exp, exp.length);
  1570. // if exponent is 65537 (0x10001), use minimum window size
  1571. if ((ebits != 17) || (exp[0] != 65537)) {
  1572. while (ebits > bnExpModThreshTable[wbits]) {
  1573. wbits++;
  1574. }
  1575. }
  1576. // Calculate appropriate table size
  1577. int tblmask = 1 << wbits;
  1578. // Allocate table for precomputed odd powers of base in Montgomery form
  1579. int[][] table = new int[tblmask][];
  1580. for (int i=0; i < tblmask; i++)
  1581. table[i] = new int[modLen];
  1582. // Compute the modular inverse of the least significant 64-bit
  1583. // digit of the modulus
  1584. long n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);
  1585. long inv = -MutableBigInteger.inverseMod64(n0);
  1586. // Convert base to Montgomery form
  1587. int[] a = leftShift(base, base.length, modLen << 5);
  1588. MutableBigInteger q = new MutableBigInteger(),
  1589. a2 = new MutableBigInteger(a),
  1590. b2 = new MutableBigInteger(mod);
  1591. b2.normalize(); // MutableBigInteger.divide() assumes that its
  1592. // divisor is in normal form.
  1593. MutableBigInteger r= a2.divide(b2, q);
  1594. table[0] = r.toIntArray();
  1595. // Pad table[0] with leading zeros so its length is at least modLen
  1596. if (table[0].length < modLen) {
  1597. int offset = modLen - table[0].length;
  1598. int[] t2 = new int[modLen];
  1599. System.arraycopy(table[0], 0, t2, offset, table[0].length);
  1600. table[0] = t2;
  1601. }
  1602. // Set b to the square of the base
  1603. int[] b = montgomerySquare(table[0], mod, modLen, inv, null);
  1604. // Set t to high half of b
  1605. int[] t = Arrays.copyOf(b, modLen);
  1606. // Fill in the table with odd powers of the base
  1607. for (int i=1; i < tblmask; i++) {
  1608. table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);
  1609. }
  1610. // Pre load the window that slides over the exponent
  1611. int bitpos = 1 << ((ebits-1) & (32-1));
  1612. int buf = 0;
  1613. int elen = exp.length;
  1614. int eIndex = 0;
  1615. for (int i = 0; i <= wbits; i++) {
  1616. buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
  1617. bitpos >>>= 1;
  1618. if (bitpos == 0) {
  1619. eIndex++;
  1620. bitpos = 1 << (32-1);
  1621. elen--;
  1622. }
  1623. }
  1624. int multpos = ebits;
  1625. // The first iteration, which is hoisted out of the main loop
  1626. ebits--;
  1627. boolean isone = true;
  1628. multpos = ebits - wbits;
  1629. while ((buf & 1) == 0) {
  1630. buf >>>= 1;
  1631. multpos++;
  1632. }
  1633. int[] mult = table[buf >>> 1];
  1634. buf = 0;
  1635. if (multpos == ebits)
  1636. isone = false;
  1637. // The main loop
  1638. while (true) {
  1639. ebits--;
  1640. // Advance the window
  1641. buf <<= 1;
  1642. if (elen != 0) {
  1643. buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
  1644. bitpos >>>= 1;
  1645. if (bitpos == 0) {
  1646. eIndex++;
  1647. bitpos = 1 << (32-1);
  1648. elen--;
  1649. }
  1650. }
  1651. // Examine the window for pending multiplies
  1652. if ((buf & tblmask) != 0) {
  1653. multpos = ebits - wbits;
  1654. while ((buf & 1) == 0) {
  1655. buf >>>= 1;
  1656. multpos++;
  1657. }
  1658. mult = table[buf >>> 1];
  1659. buf = 0;
  1660. }
  1661. // Perform multiply
  1662. if (ebits == multpos) {
  1663. if (isone) {
  1664. b = mult.clone();
  1665. isone = false;
  1666. } else {
  1667. t = b;
  1668. a = montgomeryMultiply(t, mult, mod, modLen, inv, a);
  1669. t = a; a = b; b = t;
  1670. }
  1671. }
  1672. // Check if done
  1673. if (ebits == 0)
  1674. break;
  1675. // Square the input
  1676. if (!isone) {
  1677. t = b;
  1678. a = montgomerySquare(t, mod, modLen, inv, a);
  1679. t = a; a = b; b = t;
  1680. }
  1681. }
  1682. // Convert result out of Montgomery form and return
  1683. int[] t2 = new int[2*modLen];
  1684. System.arraycopy(b, 0, t2, modLen, modLen);
  1685. b = montReduce(t2, mod, modLen, (int)inv);
  1686. t2 = Arrays.copyOf(b, modLen);
  1687. return new BigInteger(1, t2);
  1688. }
  1689. static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
  1690. int c=0;
  1691. int len = mlen;
  1692. int offset=0;
  1693. do {
  1694. int nEnd = n[n.length-1-offset];
  1695. int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
  1696. c += addOne(n, offset, mlen, carry);
  1697. offset++;
  1698. } while (--len > 0);
  1699. while (c > 0)
  1700. c += subN(n, mod, mlen);
  1701. while (intArrayCmpToLen(n, mod, mlen) >= 0)
  1702. subN(n, mod, mlen);
  1703. return n;
  1704. }
  1705. /*
  1706. * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
  1707. * equal to, or greater than arg2 up to length len.
  1708. */
  1709. static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
  1710. for (int i=0; i < len; i++) {
  1711. long b1 = arg1[i] & LONG_MASK;
  1712. long b2 = arg2[i] & LONG_MASK;
  1713. if (b1 < b2)
  1714. return -1;
  1715. if (b1 > b2)
  1716. return 1;
  1717. }
  1718. return 0;
  1719. }
  1720. static int subN(int[] a, int[] b, int len) {
  1721. long sum = 0;
  1722. while (--len >= 0) {
  1723. sum = (a[len] & LONG_MASK) -
  1724. (b[len] & LONG_MASK) + (sum >> 32);
  1725. a[len] = (int)sum;
  1726. }
  1727. return (int)(sum >> 32);
  1728. }
  1729. static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
  1730. implMulAddCheck(out, in, offset, len, k);
  1731. return implMulAdd(out, in, offset, len, k);
  1732. }
  1733. static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {
  1734. if (len > in.length) {
  1735. throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);
  1736. }
  1737. if (offset < 0) {
  1738. throw new IllegalArgumentException("input offset is invalid: " + offset);
  1739. }
  1740. if (offset > (out.length - 1)) {
  1741. throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));
  1742. }
  1743. if (len > (out.length - offset)) {
  1744. throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));
  1745. }
  1746. }
  1747. static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {
  1748. long kLong = k & LONG_MASK;
  1749. long carry = 0;
  1750. offset = out.length-offset - 1;
  1751. for (int j=len-1; j >= 0; j--) {
  1752. long product = (in[j] & LONG_MASK) * kLong +
  1753. (out[offset] & LONG_MASK) + carry;
  1754. out[offset--] = (int)product;
  1755. carry = product >>> 32;
  1756. }
  1757. return (int)carry;
  1758. }
  1759. static int addOne(int[] a, int offset, int mlen, int carry) {
  1760. offset = a.length-1-mlen-offset;
  1761. long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
  1762. a[offset] = (int)t;
  1763. if ((t >>> 32) == 0)
  1764. return 0;
  1765. while (--mlen >= 0) {
  1766. if (--offset < 0) { // Carry out of number
  1767. return 1;
  1768. } else {
  1769. a[offset]++;
  1770. if (a[offset] != 0)
  1771. return 0;
  1772. }
  1773. }
  1774. return 1;
  1775. }
  1776. BigInteger modPow2(BigInteger exponent, int p) {
  1777. /*
  1778. * Perform exponentiation using repeated squaring trick, chopping off
  1779. * high order bits as indicated by modulus.
  1780. */
  1781. BigInteger result = ONE;
  1782. BigInteger baseToPow2 = this.mod2(p);
  1783. int expOffset = 0;
  1784. int limit = exponent.bitLength();
  1785. if (this.testBit(0))
  1786. limit = (p-1) < limit ? (p-1) : limit;
  1787. while (expOffset < limit) {
  1788. if (exponent.testBit(expOffset))
  1789. result = result.multiply(baseToPow2).mod2(p);
  1790. expOffset++;
  1791. if (expOffset < limit)
  1792. baseToPow2 = baseToPow2.square().mod2(p);
  1793. }
  1794. return result;
  1795. }
  1796. BigInteger mod2(int p) {
  1797. if (bitLength() <= p)
  1798. return this;
  1799. // Copy remaining ints of mag
  1800. int numInts = (p + 31) >>> 5;
  1801. int[] mag = new int[numInts];
  1802. System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);
  1803. // Mask out any excess bits
  1804. int excessBits = (numInts << 5) - p;
  1805. mag[0] &= (1L << (32-excessBits)) - 1;
  1806. return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
  1807. }
  1808. BigInteger modInverse(BigInteger m) {
  1809. if (m.signum != 1)
  1810. throw new ArithmeticException("BigInteger: modulus not positive");
  1811. if (m.equals(ONE))
  1812. return ZERO;
  1813. // Calculate (this mod m)
  1814. BigInteger modVal = this;
  1815. if (signum < 0 || (this.compareMagnitude(m) >= 0))
  1816. modVal = this.mod(m);
  1817. if (modVal.equals(ONE))
  1818. return ONE;
  1819. MutableBigInteger a = new MutableBigInteger(modVal);
  1820. MutableBigInteger b = new MutableBigInteger(m);
  1821. MutableBigInteger result = a.mutableModInverse(b);
  1822. return result.toBigInteger(1);
  1823. }
  1824. // Shift Operations
  1825. BigInteger shiftLeft(int n) {
  1826. if (signum == 0)
  1827. return ZERO;
  1828. if (n > 0) {
  1829. return new BigInteger(shiftLeft(mag, n), signum);
  1830. } else if (n == 0) {
  1831. return this;
  1832. } else {
  1833. // Possible int overflow in (-n) is not a trouble,
  1834. // because shiftRightImpl considers its argument unsigned
  1835. return shiftRightImpl(-n);
  1836. }
  1837. }
  1838. static int[] shiftLeft(int[] mag, int n) {
  1839. int nInts = n >>> 5;
  1840. int nBits = n & 0x1f;
  1841. int magLen = mag.length;
  1842. int newMag[] = null;
  1843. if (nBits == 0) {
  1844. newMag = new int[magLen + nInts];
  1845. System.arraycopy(mag, 0, newMag, 0, magLen);
  1846. } else {
  1847. int i = 0;
  1848. int nBits2 = 32 - nBits;
  1849. int highBits = mag[0] >>> nBits2;
  1850. if (highBits != 0) {
  1851. newMag = new int[magLen + nInts + 1];
  1852. newMag[i++] = highBits;
  1853. } else {
  1854. newMag = new int[magLen + nInts];
  1855. }
  1856. int j=0;
  1857. while (j < magLen-1)
  1858. newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
  1859. newMag[i] = mag[j] << nBits;
  1860. }
  1861. return newMag;
  1862. }
  1863. BigInteger shiftRight(int n) {
  1864. if (signum == 0)
  1865. return ZERO;
  1866. if (n > 0) {
  1867. return shiftRightImpl(n);
  1868. } else if (n == 0) {
  1869. return this;
  1870. } else {
  1871. // Possible int overflow in {@code -n} is not a trouble,
  1872. // because shiftLeft considers its argument unsigned
  1873. return new BigInteger(shiftLeft(mag, -n), signum);
  1874. }
  1875. }
  1876. BigInteger shiftRightImpl(int n) {
  1877. int nInts = n >>> 5;
  1878. int nBits = n & 0x1f;
  1879. int magLen = mag.length;
  1880. int newMag[] = null;
  1881. // Special case: entire contents shifted off the end
  1882. if (nInts >= magLen)
  1883. return (signum >= 0 ? ZERO : negConst[1]);
  1884. if (nBits == 0) {
  1885. int newMagLen = magLen - nInts;
  1886. newMag = Arrays.copyOf(mag, newMagLen);
  1887. } else {
  1888. int i = 0;
  1889. int highBits = mag[0] >>> nBits;
  1890. if (highBits != 0) {
  1891. newMag = new int[magLen - nInts];
  1892. newMag[i++] = highBits;
  1893. } else {
  1894. newMag = new int[magLen - nInts -1];
  1895. }
  1896. int nBits2 = 32 - nBits;
  1897. int j=0;
  1898. while (j < magLen - nInts - 1)
  1899. newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
  1900. }
  1901. if (signum < 0) {
  1902. // Find out whether any one-bits were shifted off the end.
  1903. boolean onesLost = false;
  1904. for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
  1905. onesLost = (mag[i] != 0);
  1906. if (!onesLost && nBits != 0)
  1907. onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
  1908. if (onesLost)
  1909. newMag = javaIncrement(newMag);
  1910. }
  1911. return new BigInteger(newMag, signum);
  1912. }
  1913. int[] javaIncrement(int[] val) {
  1914. int lastSum = 0;
  1915. for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
  1916. lastSum = (val[i] += 1);
  1917. if (lastSum == 0) {
  1918. val = new int[val.length+1];
  1919. val[0] = 1;
  1920. }
  1921. return val;
  1922. }
  1923. // Bitwise Operations
  1924. BigInteger and(BigInteger val) {
  1925. int[] result = new int[Math.max(intLength(), val.intLength())];
  1926. for (int i=0; i < result.length; i++)
  1927. result[i] = (getInt(result.length-i-1)
  1928. & val.getInt(result.length-i-1));
  1929. return valueOf(result);
  1930. }
  1931. BigInteger or(BigInteger val) {
  1932. int[] result = new int[Math.max(intLength(), val.intLength())];
  1933. for (int i=0; i < result.length; i++)
  1934. result[i] = (getInt(result.length-i-1)
  1935. | val.getInt(result.length-i-1));
  1936. return valueOf(result);
  1937. }
  1938. BigInteger xor(BigInteger val) {
  1939. int[] result = new int[Math.max(intLength(), val.intLength())];
  1940. for (int i=0; i < result.length; i++)
  1941. result[i] = (getInt(result.length-i-1)
  1942. ^ val.getInt(result.length-i-1));
  1943. return valueOf(result);
  1944. }
  1945. BigInteger not() {
  1946. int[] result = new int[intLength()];
  1947. for (int i=0; i < result.length; i++)
  1948. result[i] = ~getInt(result.length-i-1);
  1949. return valueOf(result);
  1950. }
  1951. BigInteger andNot(BigInteger val) {
  1952. int[] result = new int[Math.max(intLength(), val.intLength())];
  1953. for (int i=0; i < result.length; i++)
  1954. result[i] = (getInt(result.length-i-1)
  1955. & ~val.getInt(result.length-i-1));
  1956. return valueOf(result);
  1957. }
  1958. // Single Bit Operations
  1959. boolean testBit(int n) {
  1960. if (n < 0)
  1961. throw new ArithmeticException("Negative bit address");
  1962. return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
  1963. }
  1964. BigInteger setBit(int n) {
  1965. if (n < 0)
  1966. throw new ArithmeticException("Negative bit address");
  1967. int intNum = n >>> 5;
  1968. int[] result = new int[Math.max(intLength(), intNum+2)];
  1969. for (int i=0; i < result.length; i++)
  1970. result[result.length-i-1] = getInt(i);
  1971. result[result.length-intNum-1] |= (1 << (n & 31));
  1972. return valueOf(result);
  1973. }
  1974. BigInteger clearBit(int n) {
  1975. if (n < 0)
  1976. throw new ArithmeticException("Negative bit address");
  1977. int intNum = n >>> 5;
  1978. int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
  1979. for (int i=0; i < result.length; i++)
  1980. result[result.length-i-1] = getInt(i);
  1981. result[result.length-intNum-1] &= ~(1 << (n & 31));
  1982. return valueOf(result);
  1983. }
  1984. BigInteger flipBit(int n) {
  1985. if (n < 0)
  1986. throw new ArithmeticException("Negative bit address");
  1987. int intNum = n >>> 5;
  1988. int[] result = new int[Math.max(intLength(), intNum+2)];
  1989. for (int i=0; i < result.length; i++)
  1990. result[result.length-i-1] = getInt(i);
  1991. result[result.length-intNum-1] ^= (1 << (n & 31));
  1992. return valueOf(result);
  1993. }
  1994. int getLowestSetBit() {
  1995. @SuppressWarnings("deprecation") int lsb = lowestSetBit - 2;
  1996. if (lsb == -2) { // lowestSetBit not initialized yet
  1997. lsb = 0;
  1998. if (signum == 0) {
  1999. lsb -= 1;
  2000. } else {
  2001. // Search for lowest order nonzero int
  2002. int i,b;
  2003. for (i=0; (b = getInt(i)) == 0; i++)
  2004. ;
  2005. lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
  2006. }
  2007. lowestSetBit = lsb + 2;
  2008. }
  2009. return lsb;
  2010. }
  2011. // Miscellaneous Bit Operations
  2012. int bitLength() {
  2013. @SuppressWarnings("deprecation") int n = bitLength - 1;
  2014. if (n == -1) { // bitLength not initialized yet
  2015. int[] m = mag;
  2016. int len = m.length;
  2017. if (len == 0) {
  2018. n = 0; // offset by one to initialize
  2019. } else {
  2020. // Calculate the bit length of the magnitude
  2021. int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
  2022. if (signum < 0) {
  2023. // Check if magnitude is a power of two
  2024. boolean pow2 = (Integer.bitCount(mag[0]) == 1);
  2025. for (int i=1; i< len && pow2; i++)
  2026. pow2 = (mag[i] == 0);
  2027. n = (pow2 ? magBitLength -1 : magBitLength);
  2028. } else {
  2029. n = magBitLength;
  2030. }
  2031. }
  2032. bitLength = n + 1;
  2033. }
  2034. return n;
  2035. }
  2036. int bitCount() {
  2037. @SuppressWarnings("deprecation") int bc = bitCount - 1;
  2038. if (bc == -1) { // bitCount not initialized yet
  2039. bc = 0; // offset by one to initialize
  2040. // Count the bits in the magnitude
  2041. for (int i=0; i < mag.length; i++)
  2042. bc += Integer.bitCount(mag[i]);
  2043. if (signum < 0) {
  2044. // Count the trailing zeros in the magnitude
  2045. int magTrailingZeroCount = 0, j;
  2046. for (j=mag.length-1; mag[j] == 0; j--)
  2047. magTrailingZeroCount += 32;
  2048. magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
  2049. bc += magTrailingZeroCount - 1;
  2050. }
  2051. bitCount = bc + 1;
  2052. }
  2053. return bc;
  2054. }
  2055. // Primality Testing
  2056. boolean isProbablePrime(int certainty) {
  2057. if (certainty <= 0)
  2058. return true;
  2059. BigInteger w = this.abs();
  2060. if (w.equals(TWO))
  2061. return true;
  2062. if (!w.testBit(0) || w.equals(ONE))
  2063. return false;
  2064. return w.primeToCertainty(certainty, null);
  2065. }
  2066. // Comparison Operations
  2067. int compareTo(BigInteger val) {
  2068. if (signum == val.signum) {
  2069. switch (signum) {
  2070. case 1:
  2071. return compareMagnitude(val);
  2072. case -1:
  2073. return val.compareMagnitude(this);
  2074. default:
  2075. return 0;
  2076. }
  2077. }
  2078. return signum > val.signum ? 1 : -1;
  2079. }
  2080. const int compareMagnitude(BigInteger val) {
  2081. int[] m1 = mag;
  2082. int len1 = m1.length;
  2083. int[] m2 = val.mag;
  2084. int len2 = m2.length;
  2085. if (len1 < len2)
  2086. return -1;
  2087. if (len1 > len2)
  2088. return 1;
  2089. for (int i = 0; i < len1; i++) {
  2090. int a = m1[i];
  2091. int b = m2[i];
  2092. if (a != b)
  2093. return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
  2094. }
  2095. return 0;
  2096. }
  2097. const int compareMagnitude(long val) {
  2098. assert val != Long.MIN_VALUE;
  2099. int[] m1 = mag;
  2100. int len = m1.length;
  2101. if (len > 2) {
  2102. return 1;
  2103. }
  2104. if (val < 0) {
  2105. val = -val;
  2106. }
  2107. int highWord = (int)(val >>> 32);
  2108. if (highWord == 0) {
  2109. if (len < 1)
  2110. return -1;
  2111. if (len > 1)
  2112. return 1;
  2113. int a = m1[0];
  2114. int b = (int)val;
  2115. if (a != b) {
  2116. return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
  2117. }
  2118. return 0;
  2119. } else {
  2120. if (len < 2)
  2121. return -1;
  2122. int a = m1[0];
  2123. int b = highWord;
  2124. if (a != b) {
  2125. return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
  2126. }
  2127. a = m1[1];
  2128. b = (int)val;
  2129. if (a != b) {
  2130. return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
  2131. }
  2132. return 0;
  2133. }
  2134. }
  2135. boolean equals(Object x) {
  2136. // This test is just an optimization, which may or may not help
  2137. if (x == this)
  2138. return true;
  2139. if (!(x instanceof BigInteger))
  2140. return false;
  2141. BigInteger xInt = (BigInteger) x;
  2142. if (xInt.signum != signum)
  2143. return false;
  2144. int[] m = mag;
  2145. int len = m.length;
  2146. int[] xm = xInt.mag;
  2147. if (len != xm.length)
  2148. return false;
  2149. for (int i = 0; i < len; i++)
  2150. if (xm[i] != m[i])
  2151. return false;
  2152. return true;
  2153. }
  2154. BigInteger min(BigInteger val) {
  2155. return (compareTo(val) < 0 ? this : val);
  2156. }
  2157. BigInteger max(BigInteger val) {
  2158. return (compareTo(val) > 0 ? this : val);
  2159. }
  2160. // Hash Function
  2161. int hashCode() {
  2162. int hashCode = 0;
  2163. for (int i=0; i < mag.length; i++)
  2164. hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
  2165. return hashCode * signum;
  2166. }
  2167. String toString(int radix) {
  2168. if (signum == 0)
  2169. return "0";
  2170. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  2171. radix = 10;
  2172. // If it's small enough, use smallToString.
  2173. if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD)
  2174. return smallToString(radix);
  2175. // Otherwise use recursive toString, which requires positive arguments.
  2176. // The results will be concatenated into this StringBuilder
  2177. StringBuilder sb = new StringBuilder();
  2178. if (signum < 0) {
  2179. toString(this.negate(), sb, radix, 0);
  2180. sb.insert(0, '-');
  2181. }
  2182. else
  2183. toString(this, sb, radix, 0);
  2184. return sb.toString();
  2185. }
  2186. String smallToString(int radix) {
  2187. if (signum == 0) {
  2188. return "0";
  2189. }
  2190. // Compute upper bound on number of digit groups and allocate space
  2191. int maxNumDigitGroups = (4*mag.length + 6)/7;
  2192. String digitGroup[] = new String[maxNumDigitGroups];
  2193. // Translate number to string, a digit group at a time
  2194. BigInteger tmp = this.abs();
  2195. int numGroups = 0;
  2196. while (tmp.signum != 0) {
  2197. BigInteger d = longRadix[radix];
  2198. MutableBigInteger q = new MutableBigInteger(),
  2199. a = new MutableBigInteger(tmp.mag),
  2200. b = new MutableBigInteger(d.mag);
  2201. MutableBigInteger r = a.divide(b, q);
  2202. BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
  2203. BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
  2204. digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
  2205. tmp = q2;
  2206. }
  2207. // Put sign (if any) and first digit group into result buffer
  2208. StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
  2209. if (signum < 0) {
  2210. buf.append('-');
  2211. }
  2212. buf.append(digitGroup[numGroups-1]);
  2213. // Append remaining digit groups padded with leading zeros
  2214. for (int i=numGroups-2; i >= 0; i--) {
  2215. // Prepend (any) leading zeros for this digit group
  2216. int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
  2217. if (numLeadingZeros != 0) {
  2218. buf.append(zeros[numLeadingZeros]);
  2219. }
  2220. buf.append(digitGroup[i]);
  2221. }
  2222. return buf.toString();
  2223. }
  2224. static void toString(BigInteger u, StringBuilder sb, int radix,
  2225. int digits) {
  2226. /* If we're smaller than a certain threshold, use the smallToString
  2227. method, padding with leading zeroes when necessary. */
  2228. if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
  2229. String s = u.smallToString(radix);
  2230. // Pad with internal zeros if necessary.
  2231. // Don't pad if we're at the beginning of the string.
  2232. if ((s.length() < digits) && (sb.length() > 0)) {
  2233. for (int i=s.length(); i < digits; i++) { // May be a faster way to
  2234. sb.append('0'); // do this?
  2235. }
  2236. }
  2237. sb.append(s);
  2238. return;
  2239. }
  2240. int b, n;
  2241. b = u.bitLength();
  2242. // Calculate a value for n in the equation radix^(2^n) = u
  2243. // and subtract 1 from that value. This is used to find the
  2244. // cache index that contains the best value to divide u.
  2245. n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);
  2246. BigInteger v = getRadixConversionCache(radix, n);
  2247. BigInteger[] results;
  2248. results = u.divideAndRemainder(v);
  2249. int expectedDigits = 1 << n;
  2250. // Now recursively build the two halves of each number.
  2251. toString(results[0], sb, radix, digits-expectedDigits);
  2252. toString(results[1], sb, radix, expectedDigits);
  2253. }
  2254. static BigInteger getRadixConversionCache(int radix, int exponent) {
  2255. BigInteger[] cacheLine = powerCache[radix]; // volatile read
  2256. if (exponent < cacheLine.length) {
  2257. return cacheLine[exponent];
  2258. }
  2259. int oldLength = cacheLine.length;
  2260. cacheLine = Arrays.copyOf(cacheLine, exponent + 1);
  2261. for (int i = oldLength; i <= exponent; i++) {
  2262. cacheLine[i] = cacheLine[i - 1].pow(2);
  2263. }
  2264. BigInteger[][] pc = powerCache; // volatile read again
  2265. if (exponent >= pc[radix].length) {
  2266. pc = pc.clone();
  2267. pc[radix] = cacheLine;
  2268. powerCache = pc; // volatile write, publish
  2269. }
  2270. return cacheLine[exponent];
  2271. }
  2272. /* zero[i] is a string of i consecutive zeros. */
  2273. static String zeros[] = new String[64];
  2274. static {
  2275. zeros[63] =
  2276. "000000000000000000000000000000000000000000000000000000000000000";
  2277. for (int i=0; i < 63; i++)
  2278. zeros[i] = zeros[63].substring(0, i);
  2279. }
  2280. String toString() {
  2281. return toString(10);
  2282. }
  2283. byte[] toByteArray() {
  2284. int byteLen = bitLength()/8 + 1;
  2285. byte[] byteArray = new byte[byteLen];
  2286. for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
  2287. if (bytesCopied == 4) {
  2288. nextInt = getInt(intIndex++);
  2289. bytesCopied = 1;
  2290. } else {
  2291. nextInt >>>= 8;
  2292. bytesCopied++;
  2293. }
  2294. byteArray[i] = (byte)nextInt;
  2295. }
  2296. return byteArray;
  2297. }
  2298. int intValue() {
  2299. int result = 0;
  2300. result = getInt(0);
  2301. return result;
  2302. }
  2303. long longValue() {
  2304. long result = 0;
  2305. for (int i=1; i >= 0; i--)
  2306. result = (result << 32) + (getInt(i) & LONG_MASK);
  2307. return result;
  2308. }
  2309. float floatValue() {
  2310. if (signum == 0) {
  2311. return 0.0f;
  2312. }
  2313. int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
  2314. // exponent == floor(log2(abs(this)))
  2315. if (exponent < Long.SIZE - 1) {
  2316. return longValue();
  2317. } else if (exponent > Float.MAX_EXPONENT) {
  2318. return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
  2319. }
  2320. /*
  2321. * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
  2322. * one bit. To make rounding easier, we pick out the top
  2323. * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
  2324. * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
  2325. * bits, and signifFloor the top SIGNIFICAND_WIDTH.
  2326. *
  2327. * It helps to consider the real number signif = abs(this) *
  2328. * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
  2329. */
  2330. int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH;
  2331. int twiceSignifFloor;
  2332. // twiceSignifFloor will be == abs().shiftRight(shift).intValue()
  2333. // We do the shift into an int directly to improve performance.
  2334. int nBits = shift & 0x1f;
  2335. int nBits2 = 32 - nBits;
  2336. if (nBits == 0) {
  2337. twiceSignifFloor = mag[0];
  2338. } else {
  2339. twiceSignifFloor = mag[0] >>> nBits;
  2340. if (twiceSignifFloor == 0) {
  2341. twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits);
  2342. }
  2343. }
  2344. int signifFloor = twiceSignifFloor >> 1;
  2345. signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit
  2346. /*
  2347. * We round up if either the fractional part of signif is strictly
  2348. * greater than 0.5 (which is true if the 0.5 bit is set and any lower
  2349. * bit is set), or if the fractional part of signif is >= 0.5 and
  2350. * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
  2351. * are set). This is equivalent to the desired HALF_EVEN rounding.
  2352. */
  2353. boolean increment = (twiceSignifFloor & 1) != 0
  2354. && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
  2355. int signifRounded = increment ? signifFloor + 1 : signifFloor;
  2356. int bits = ((exponent + FloatConsts.EXP_BIAS))
  2357. << (FloatConsts.SIGNIFICAND_WIDTH - 1);
  2358. bits += signifRounded;
  2359. /*
  2360. * If signifRounded == 2^24, we'd need to set all of the significand
  2361. * bits to zero and add 1 to the exponent. This is exactly the behavior
  2362. * we get from just adding signifRounded to bits directly. If the
  2363. * exponent is Float.MAX_EXPONENT, we round up (correctly) to
  2364. * Float.POSITIVE_INFINITY.
  2365. */
  2366. bits |= signum & FloatConsts.SIGN_BIT_MASK;
  2367. return Float.intBitsToFloat(bits);
  2368. }
  2369. double doubleValue() {
  2370. if (signum == 0) {
  2371. return 0.0;
  2372. }
  2373. int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
  2374. // exponent == floor(log2(abs(this))Double)
  2375. if (exponent < Long.SIZE - 1) {
  2376. return longValue();
  2377. } else if (exponent > Double.MAX_EXPONENT) {
  2378. return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
  2379. }
  2380. /*
  2381. * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
  2382. * one bit. To make rounding easier, we pick out the top
  2383. * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
  2384. * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
  2385. * bits, and signifFloor the top SIGNIFICAND_WIDTH.
  2386. *
  2387. * It helps to consider the real number signif = abs(this) *
  2388. * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
  2389. */
  2390. int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;
  2391. long twiceSignifFloor;
  2392. // twiceSignifFloor will be == abs().shiftRight(shift).longValue()
  2393. // We do the shift into a long directly to improve performance.
  2394. int nBits = shift & 0x1f;
  2395. int nBits2 = 32 - nBits;
  2396. int highBits;
  2397. int lowBits;
  2398. if (nBits == 0) {
  2399. highBits = mag[0];
  2400. lowBits = mag[1];
  2401. } else {
  2402. highBits = mag[0] >>> nBits;
  2403. lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);
  2404. if (highBits == 0) {
  2405. highBits = lowBits;
  2406. lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);
  2407. }
  2408. }
  2409. twiceSignifFloor = ((highBits & LONG_MASK) << 32)
  2410. | (lowBits & LONG_MASK);
  2411. long signifFloor = twiceSignifFloor >> 1;
  2412. signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit
  2413. /*
  2414. * We round up if either the fractional part of signif is strictly
  2415. * greater than 0.5 (which is true if the 0.5 bit is set and any lower
  2416. * bit is set), or if the fractional part of signif is >= 0.5 and
  2417. * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
  2418. * are set). This is equivalent to the desired HALF_EVEN rounding.
  2419. */
  2420. boolean increment = (twiceSignifFloor & 1) != 0
  2421. && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
  2422. long signifRounded = increment ? signifFloor + 1 : signifFloor;
  2423. long bits = (long) ((exponent + DoubleConsts.EXP_BIAS))
  2424. << (DoubleConsts.SIGNIFICAND_WIDTH - 1);
  2425. bits += signifRounded;
  2426. /*
  2427. * If signifRounded == 2^53, we'd need to set all of the significand
  2428. * bits to zero and add 1 to the exponent. This is exactly the behavior
  2429. * we get from just adding signifRounded to bits directly. If the
  2430. * exponent is Double.MAX_EXPONENT, we round up (correctly) to
  2431. * Double.POSITIVE_INFINITY.
  2432. */
  2433. bits |= signum & DoubleConsts.SIGN_BIT_MASK;
  2434. return Double.longBitsToDouble(bits);
  2435. }
  2436. static int[] stripLeadingZeroInts(int val[]) {
  2437. int vlen = val.length;
  2438. int keep;
  2439. // Find first nonzero byte
  2440. for (keep = 0; keep < vlen && val[keep] == 0; keep++)
  2441. ;
  2442. return java.util.Arrays.copyOfRange(val, keep, vlen);
  2443. }
  2444. static int[] trustedStripLeadingZeroInts(int val[]) {
  2445. int vlen = val.length;
  2446. int keep;
  2447. // Find first nonzero byte
  2448. for (keep = 0; keep < vlen && val[keep] == 0; keep++)
  2449. ;
  2450. return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);
  2451. }
  2452. static int[] stripLeadingZeroBytes(byte a[]) {
  2453. int byteLength = a.length;
  2454. int keep;
  2455. // Find first nonzero byte
  2456. for (keep = 0; keep < byteLength && a[keep] == 0; keep++)
  2457. ;
  2458. // Allocate new array and copy relevant part of input array
  2459. int intLength = ((byteLength - keep) + 3) >>> 2;
  2460. int[] result = new int[intLength];
  2461. int b = byteLength - 1;
  2462. for (int i = intLength-1; i >= 0; i--) {
  2463. result[i] = a[b--] & 0xff;
  2464. int bytesRemaining = b - keep + 1;
  2465. int bytesToTransfer = Math.min(3, bytesRemaining);
  2466. for (int j=8; j <= (bytesToTransfer << 3); j += 8)
  2467. result[i] |= ((a[b--] & 0xff) << j);
  2468. }
  2469. return result;
  2470. }
  2471. static int[] makePositive(byte a[]) {
  2472. int keep, k;
  2473. int byteLength = a.length;
  2474. // Find first non-sign (0xff) byte of input
  2475. for (keep=0; keep < byteLength && a[keep] == -1; keep++)
  2476. ;
  2477. /* Allocate output array. If all non-sign bytes are 0x00, we must
  2478. * allocate space for one extra output byte. */
  2479. for (k=keep; k < byteLength && a[k] == 0; k++)
  2480. ;
  2481. int extraByte = (k == byteLength) ? 1 : 0;
  2482. int intLength = ((byteLength - keep + extraByte) + 3) >>> 2;
  2483. int result[] = new int[intLength];
  2484. /* Copy one's complement of input into output, leaving extra
  2485. * byte (if it exists) == 0x00 */
  2486. int b = byteLength - 1;
  2487. for (int i = intLength-1; i >= 0; i--) {
  2488. result[i] = a[b--] & 0xff;
  2489. int numBytesToTransfer = Math.min(3, b-keep+1);
  2490. if (numBytesToTransfer < 0)
  2491. numBytesToTransfer = 0;
  2492. for (int j=8; j <= 8*numBytesToTransfer; j += 8)
  2493. result[i] |= ((a[b--] & 0xff) << j);
  2494. // Mask indicates which bits must be complemented
  2495. int mask = -1 >>> (8*(3-numBytesToTransfer));
  2496. result[i] = ~result[i] & mask;
  2497. }
  2498. // Add one to one's complement to generate two's complement
  2499. for (int i=result.length-1; i >= 0; i--) {
  2500. result[i] = (int)((result[i] & LONG_MASK) + 1);
  2501. if (result[i] != 0)
  2502. break;
  2503. }
  2504. return result;
  2505. }
  2506. static int[] makePositive(int a[]) {
  2507. int keep, j;
  2508. // Find first non-sign (0xffffffff) int of input
  2509. for (keep=0; keep < a.length && a[keep] == -1; keep++)
  2510. ;
  2511. /* Allocate output array. If all non-sign ints are 0x00, we must
  2512. * allocate space for one extra output int. */
  2513. for (j=keep; j < a.length && a[j] == 0; j++)
  2514. ;
  2515. int extraInt = (j == a.length ? 1 : 0);
  2516. int result[] = new int[a.length - keep + extraInt];
  2517. /* Copy one's complement of input into output, leaving extra
  2518. * int (if it exists) == 0x00 */
  2519. for (int i = keep; i < a.length; i++)
  2520. result[i - keep + extraInt] = ~a[i];
  2521. // Add one to one's complement to generate two's complement
  2522. for (int i=result.length-1; ++result[i] == 0; i--)
  2523. ;
  2524. return result;
  2525. }
  2526. /*
  2527. * The following two arrays are used for fast String conversions. Both
  2528. * are indexed by radix. The first is the number of digits of the given
  2529. * radix that can fit in a Java long without "going negative", i.e., the
  2530. * highest integer n such that radix**n < 2**63. The second is the
  2531. * "long radix" that tears each number into "long digits", each of which
  2532. * consists of the number of digits in the corresponding element in
  2533. * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have
  2534. * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
  2535. * used.
  2536. */
  2537. static int digitsPerLong[] = {0, 0,
  2538. 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
  2539. 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
  2540. static BigInteger longRadix[] = {null, null,
  2541. valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
  2542. valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
  2543. valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
  2544. valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
  2545. valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
  2546. valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
  2547. valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
  2548. valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
  2549. valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
  2550. valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
  2551. valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
  2552. valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
  2553. valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
  2554. valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
  2555. valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
  2556. valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
  2557. valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
  2558. valueOf(0x41c21cb8e1000000L)};
  2559. /*
  2560. * These two arrays are the integer analogue of above.
  2561. */
  2562. static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
  2563. 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  2564. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
  2565. static int intRadix[] = {0, 0,
  2566. 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
  2567. 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
  2568. 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,
  2569. 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
  2570. 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,
  2571. 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
  2572. 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
  2573. };
  2574. int intLength() {
  2575. return (bitLength() >>> 5) + 1;
  2576. }
  2577. /* Returns sign bit */
  2578. int signBit() {
  2579. return signum < 0 ? 1 : 0;
  2580. }
  2581. /* Returns an int of sign bits */
  2582. int signInt() {
  2583. return signum < 0 ? -1 : 0;
  2584. }
  2585. int getInt(int n) {
  2586. if (n < 0)
  2587. return 0;
  2588. if (n >= mag.length)
  2589. return signInt();
  2590. int magInt = mag[mag.length-n-1];
  2591. return (signum >= 0 ? magInt :
  2592. (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
  2593. }
  2594. int firstNonzeroIntNum() {
  2595. int fn = firstNonzeroIntNum - 2;
  2596. if (fn == -2) { // firstNonzeroIntNum not initialized yet
  2597. fn = 0;
  2598. // Search for the first nonzero int
  2599. int i;
  2600. int mlen = mag.length;
  2601. for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
  2602. ;
  2603. fn = mlen - i - 1;
  2604. firstNonzeroIntNum = fn + 2; // offset by two to initialize
  2605. }
  2606. return fn;
  2607. }
  2608. static const long serialVersionUID = -8287574255936472291L;
  2609. static const ObjectStreamField[] serialPersistentFields = {
  2610. new ObjectStreamField("signum", Integer.TYPE),
  2611. new ObjectStreamField("magnitude", byte[].class),
  2612. new ObjectStreamField("bitCount", Integer.TYPE),
  2613. new ObjectStreamField("bitLength", Integer.TYPE),
  2614. new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
  2615. new ObjectStreamField("lowestSetBit", Integer.TYPE)
  2616. };
  2617. void readObject(java.io.ObjectInputStream s)
  2618. throws java.io.IOException, ClassNotFoundException {
  2619. /*
  2620. * In order to maintain compatibility with previous serialized forms,
  2621. * the magnitude of a BigInteger is serialized as an array of bytes.
  2622. * The magnitude field is used as a temporary store for the byte array
  2623. * that is deserialized. The cached computation fields should be
  2624. * transient but are serialized for compatibility reasons.
  2625. */
  2626. // prepare to read the alternate persistent fields
  2627. ObjectInputStream.GetField fields = s.readFields();
  2628. // Read the alternate persistent fields that we care about
  2629. int sign = fields.get("signum", -2);
  2630. byte[] magnitude = (byte[])fields.get("magnitude", null);
  2631. // Validate signum
  2632. if (sign < -1 || sign > 1) {
  2633. String message = "BigInteger: Invalid signum value";
  2634. if (fields.defaulted("signum"))
  2635. message = "BigInteger: Signum not present in stream";
  2636. throw new java.io.StreamCorruptedException(message);
  2637. }
  2638. int[] mag = stripLeadingZeroBytes(magnitude);
  2639. if ((mag.length == 0) != (sign == 0)) {
  2640. String message = "BigInteger: signum-magnitude mismatch";
  2641. if (fields.defaulted("magnitude"))
  2642. message = "BigInteger: Magnitude not present in stream";
  2643. throw new java.io.StreamCorruptedException(message);
  2644. }
  2645. // Commit const fields via Unsafe
  2646. UnsafeHolder.putSign(this, sign);
  2647. // Calculate mag field from magnitude and discard magnitude
  2648. UnsafeHolder.putMag(this, mag);
  2649. if (mag.length >= MAX_MAG_LENGTH) {
  2650. try {
  2651. checkRange();
  2652. } catch (ArithmeticException e) {
  2653. throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range");
  2654. }
  2655. }
  2656. }
  2657. // Support for resetting const fields while deserializing
  2658. static class UnsafeHolder {
  2659. static const sun.misc.Unsafe unsafe;
  2660. static const long signumOffset;
  2661. static const long magOffset;
  2662. static {
  2663. try {
  2664. unsafe = sun.misc.Unsafe.getUnsafe();
  2665. signumOffset = unsafe.objectFieldOffset
  2666. (BigInteger.class.getDeclaredField("signum"));
  2667. magOffset = unsafe.objectFieldOffset
  2668. (BigInteger.class.getDeclaredField("mag"));
  2669. } catch (Exception ex) {
  2670. throw new ExceptionInInitializerError(ex);
  2671. }
  2672. }
  2673. static void putSign(BigInteger bi, int sign) {
  2674. unsafe.putIntVolatile(bi, signumOffset, sign);
  2675. }
  2676. static void putMag(BigInteger bi, int[] magnitude) {
  2677. unsafe.putObjectVolatile(bi, magOffset, magnitude);
  2678. }
  2679. }
  2680. void writeObject(ObjectOutputStream s) throws IOException {
  2681. // set the values of the Serializable fields
  2682. ObjectOutputStream.PutField fields = s.putFields();
  2683. fields.put("signum", signum);
  2684. fields.put("magnitude", magSerializedForm());
  2685. // The values written for cached fields are compatible with older
  2686. // versions, but are ignored in readObject so don't otherwise matter.
  2687. fields.put("bitCount", -1);
  2688. fields.put("bitLength", -1);
  2689. fields.put("lowestSetBit", -2);
  2690. fields.put("firstNonzeroByteNum", -2);
  2691. // save them
  2692. s.writeFields();
  2693. }
  2694. byte[] magSerializedForm() {
  2695. int len = mag.length;
  2696. int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
  2697. int byteLen = (bitLen + 7) >>> 3;
  2698. byte[] result = new byte[byteLen];
  2699. for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
  2700. i >= 0; i--) {
  2701. if (bytesCopied == 4) {
  2702. nextInt = mag[intIndex--];
  2703. bytesCopied = 1;
  2704. } else {
  2705. nextInt >>>= 8;
  2706. bytesCopied++;
  2707. }
  2708. result[i] = (byte)nextInt;
  2709. }
  2710. return result;
  2711. }
  2712. long longValueExact() {
  2713. if (mag.length <= 2 && bitLength() <= 63)
  2714. return longValue();
  2715. else
  2716. throw new ArithmeticException("BigInteger out of long range");
  2717. }
  2718. int intValueExact() {
  2719. if (mag.length <= 1 && bitLength() <= 31)
  2720. return intValue();
  2721. else
  2722. throw new ArithmeticException("BigInteger out of int range");
  2723. }
  2724. short shortValueExact() {
  2725. if (mag.length <= 1 && bitLength() <= 31) {
  2726. int value = intValue();
  2727. if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)
  2728. return shortValue();
  2729. }
  2730. throw new ArithmeticException("BigInteger out of short range");
  2731. }
  2732. byte byteValueExact() {
  2733. if (mag.length <= 1 && bitLength() <= 31) {
  2734. int value = intValue();
  2735. if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)
  2736. return byteValue();
  2737. }
  2738. throw new ArithmeticException("BigInteger out of byte range");
  2739. }
  2740. static void main(String[] args) {
  2741. BigInteger a = new BigInteger(6);
  2742. a = a.pow(100);
  2743. System.out.println(a);
  2744. }
  2745. }