BigInteger.cpp 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372
  1. #include <vector>
  2. #include <algorithm>
  3. #include <cstring>
  4. #include <iterator>
  5. #include <stdexcept>
  6. #include <cstdint>
  7. #include <cassert>
  8. using std::uint64_t;
  9. class BigInteger{
  10. const int signum;
  11. std::vector<int> mag;
  12. int bitCount;
  13. int bitLength;
  14. int lowestSetBit;
  15. int firstNonzeroIntNum;
  16. const static uint64_t LONG_MASK = 0xffffffffL;
  17. static const int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
  18. static const int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
  19. static const int KARATSUBA_THRESHOLD = 80;
  20. static const int TOOM_COOK_THRESHOLD = 240;
  21. static const int KARATSUBA_SQUARE_THRESHOLD = 128;
  22. static const int TOOM_COOK_SQUARE_THRESHOLD = 216;
  23. static const int BURNIKEL_ZIEGLER_THRESHOLD = 80;
  24. static const int BURNIKEL_ZIEGLER_OFFSET = 40;
  25. static const int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
  26. static const int MULTIPLY_SQUARE_THRESHOLD = 20;
  27. static const int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
  28. BigInteger(std::vector<char> val) {
  29. assert(val.size() != 0);
  30. if (val[0] < 0) {
  31. mag = makePositive(val);
  32. signum = -1;
  33. } else {
  34. mag = stripLeadingZeroBytes(val);
  35. signum = (mag.length == 0 ? 0 : 1);
  36. }
  37. if (mag.size() >= MAX_MAG_LENGTH) {
  38. checkRange();
  39. }
  40. }
  41. BigInteger(std::vector<int> val) {
  42. assert(val.size() != 0);
  43. if (val[0] < 0) {
  44. mag = makePositive(val);
  45. signum = -1;
  46. } else {
  47. mag = trustedStripLeadingZeroInts(val);
  48. signum = (mag.size() == 0 ? 0 : 1);
  49. }
  50. if (mag.size() >= MAX_MAG_LENGTH) {
  51. checkRange();
  52. }
  53. }
  54. BigInteger(int signum, std::vector<char> magnitude) {
  55. mag = stripLeadingZeroBytes(magnitude);
  56. assert(!(signum < -1 || signum > 1));
  57. if (mag.size() == 0) {
  58. signum = 0;
  59. } else {
  60. assert(signum != 0);
  61. signum = signum;
  62. }
  63. if (mag.size() >= MAX_MAG_LENGTH) {
  64. checkRange();
  65. }
  66. }
  67. BigInteger(int signum, std::vector<int> magnitude) {
  68. mag = stripLeadingZeroInts(magnitude);
  69. assert(!(signum < -1 || signum > 1));
  70. if (this.mag.length == 0) {
  71. signum = 0;
  72. } else {
  73. assert(signum != 0);
  74. signum = signum;
  75. }
  76. if (mag.length >= MAX_MAG_LENGTH) {
  77. checkRange();
  78. }
  79. }
  80. /*
  81. * Constructs a new BigInteger using a char array with radix=10.
  82. * Sign is precalculated outside and not allowed in the val.
  83. */
  84. BigInteger(std::vector<char> val, int sign, int len) {
  85. int cursor = 0, numDigits;
  86. // Skip leading zeros and compute number of digits in magnitude
  87. while (cursor < len && Character.digit(val[cursor], 10) == 0) {
  88. cursor++;
  89. }
  90. if (cursor == len) {
  91. signum = 0;
  92. mag = ZERO.mag;
  93. return;
  94. }
  95. numDigits = len - cursor;
  96. signum = sign;
  97. // Pre-allocate array of expected size
  98. unsigned int numWords;
  99. if (len < 10) {
  100. numWords = 1;
  101. } else {
  102. uint64_t numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;
  103. if (numBits + 31 >= (1L << 32)) {
  104. reportOverflow();
  105. }
  106. numWords = (int) (numBits + 31) >>> 5;
  107. }
  108. std::vector<int> magnitude(numBits);
  109. // Process first (potentially short) digit group
  110. int firstGroupLen = numDigits % digitsPerInt[10];
  111. if (firstGroupLen == 0)
  112. firstGroupLen = digitsPerInt[10];
  113. magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen);
  114. // Process remaining digit groups
  115. while (cursor < len) {
  116. int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
  117. destructiveMulAdd(magnitude, intRadix[10], groupVal);
  118. }
  119. mag = trustedStripLeadingZeroInts(magnitude);
  120. if (mag.length >= MAX_MAG_LENGTH) {
  121. checkRange();
  122. }
  123. }
  124. int digit(char a){
  125. assert((int)(a - '0') < 10 && (int)(a - '0') >= 0);
  126. return (int)(a - '0');
  127. }
  128. // Create an integer with the digits between the two indexes
  129. // Assumes start < end. The result may be negative, but it
  130. // is to be treated as an unsigned value.
  131. int parseInt(const std::vector<char>& source, int start, int end) {
  132. int result = digit(source[start++]);
  133. for (int index = start; index < end; index++) {
  134. int nextVal = digit(source[index]);
  135. result = 10 * result + nextVal;
  136. }
  137. return result;
  138. }
  139. // bitsPerDigit in the given radix times 1024
  140. // Rounded up to avoid underallocation.
  141. static uint64_t bitsPerDigit[] = { 0, 0,
  142. 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
  143. 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
  144. 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
  145. 5253, 5295};
  146. // Multiply x array times word y in place, and add word z
  147. static void destructiveMulAdd(std::vector<int>& x, int y, int z) {
  148. // Perform the multiplication word by word
  149. uint64_t ylong = y & LONG_MASK;
  150. uint64_t zlong = z & LONG_MASK;
  151. int len = x.length;
  152. uint64_t product = 0;
  153. uint64_t carry = 0;
  154. for (int i = len-1; i >= 0; i--) {
  155. product = ylong * (x[i] & LONG_MASK) + carry;
  156. x[i] = (int)product;
  157. carry = product >>> 32;
  158. }
  159. // Perform the addition
  160. uint64_t sum = (x[len-1] & LONG_MASK) + zlong;
  161. x[len-1] = (int)sum;
  162. carry = sum >> 32;
  163. for (int i = len-2; i >= 0; i--) {
  164. sum = (x[i] & LONG_MASK) + carry;
  165. x[i] = (int)sum;
  166. carry = sum >> 32;
  167. }
  168. }
  169. BigInteger(std::string val) : BigInteger(val, 10) {
  170. }
  171. BigInteger(int numBits, std::mt19937_64& rnd) : BigInteger(1, randomBits(numBits, rnd)) {
  172. }
  173. static std::vector<char> randomBits(unsigned int numBits, std::mt19937_64& rnd) {
  174. unsigned int numBytes = (unsigned int)(((uint64_t)numBits+7)/8); // avoid overflow
  175. std::vector<char> randomBits(numBytes);
  176. std::uniform_int_distribution<char> dis(-128,127);
  177. // Generate random bytes and mask out any excess bits
  178. if (numBytes > 0) {
  179. std::generate(randomBits.begin(), randomBits.end(), [&](){return dis(rnd)});
  180. int excessBits = 8*numBytes - numBits;
  181. randomBits[0] &= (1 << (8-excessBits)) - 1;
  182. }
  183. return randomBits;
  184. }
  185. BigInteger(int bitLength, int certainty, std::mt19937_64& rnd) {
  186. BigInteger prime;
  187. assert(bitLength >= 2);
  188. prime = (bitLength < SMALL_PRIME_THRESHOLD
  189. ? smallPrime(bitLength, certainty, rnd)
  190. : largePrime(bitLength, certainty, rnd));
  191. signum = 1;
  192. mag = prime.mag;
  193. }
  194. // Minimum size in bits that the requested prime number has
  195. // before we use the large prime number generating algorithms.
  196. // The cutoff of 95 was chosen empirically for best performance.
  197. static const int SMALL_PRIME_THRESHOLD = 95;
  198. // Certainty required to meet the spec of probablePrime
  199. static const int DEFAULT_PRIME_CERTAINTY = 100;
  200. /*static BigInteger probablePrime(int bitLength, Random rnd) {
  201. if (bitLength < 2)
  202. throw new ArithmeticException("bitLength < 2");
  203. return (bitLength < SMALL_PRIME_THRESHOLD ?
  204. smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
  205. largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
  206. }
  207. static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
  208. int magLen = (bitLength + 31) >>> 5;
  209. int temp[] = new int[magLen];
  210. int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int
  211. int highMask = (highBit << 1) - 1; // Bits to keep in high int
  212. while (true) {
  213. // Construct a candidate
  214. for (int i=0; i < magLen; i++)
  215. temp[i] = rnd.nextInt();
  216. temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length
  217. if (bitLength > 2)
  218. temp[magLen-1] |= 1; // Make odd if bitlen > 2
  219. BigInteger p = new BigInteger(temp, 1);
  220. // Do cheap "pre-test" if applicable
  221. if (bitLength > 6) {
  222. long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
  223. if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
  224. (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
  225. (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
  226. continue; // Candidate is composite; try another
  227. }
  228. // All candidates of bitLength 2 and 3 are prime by this point
  229. if (bitLength < 4)
  230. return p;
  231. // Do expensive test if we survive pre-test (or it's inapplicable)
  232. if (p.primeToCertainty(certainty, rnd))
  233. return p;
  234. }
  235. }
  236. static const BigInteger SMALL_PRIME_PRODUCT
  237. = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
  238. static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
  239. BigInteger p;
  240. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  241. p.mag[p.mag.length-1] &= 0xfffffffe;
  242. // Use a sieve length likely to contain the next prime number
  243. int searchLen = getPrimeSearchLen(bitLength);
  244. BitSieve searchSieve = new BitSieve(p, searchLen);
  245. BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
  246. while ((candidate == null) || (candidate.bitLength() != bitLength)) {
  247. p = p.add(BigInteger.valueOf(2*searchLen));
  248. if (p.bitLength() != bitLength)
  249. p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
  250. p.mag[p.mag.length-1] &= 0xfffffffe;
  251. searchSieve = new BitSieve(p, searchLen);
  252. candidate = searchSieve.retrieve(p, certainty, rnd);
  253. }
  254. return candidate;
  255. }
  256. BigInteger nextProbablePrime() {
  257. if (this.signum < 0)
  258. throw new ArithmeticException("start < 0: " + this);
  259. // Handle trivial cases
  260. if ((this.signum == 0) || this.equals(ONE))
  261. return TWO;
  262. BigInteger result = this.add(ONE);
  263. // Fastpath for small numbers
  264. if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
  265. // Ensure an odd number
  266. if (!result.testBit(0))
  267. result = result.add(ONE);
  268. while (true) {
  269. // Do cheap "pre-test" if applicable
  270. if (result.bitLength() > 6) {
  271. long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
  272. if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
  273. (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
  274. (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
  275. result = result.add(TWO);
  276. continue; // Candidate is composite; try another
  277. }
  278. }
  279. // All candidates of bitLength 2 and 3 are prime by this point
  280. if (result.bitLength() < 4)
  281. return result;
  282. // The expensive test
  283. if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
  284. return result;
  285. result = result.add(TWO);
  286. }
  287. }
  288. // Start at previous even number
  289. if (result.testBit(0))
  290. result = result.subtract(ONE);
  291. // Looking for the next large prime
  292. int searchLen = getPrimeSearchLen(result.bitLength());
  293. while (true) {
  294. BitSieve searchSieve = new BitSieve(result, searchLen);
  295. BigInteger candidate = searchSieve.retrieve(result,
  296. DEFAULT_PRIME_CERTAINTY, null);
  297. if (candidate != null)
  298. return candidate;
  299. result = result.add(BigInteger.valueOf(2 * searchLen));
  300. }
  301. }
  302. static int getPrimeSearchLen(int bitLength) {
  303. if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {
  304. throw new ArithmeticException("Prime search implementation restriction on bitLength");
  305. }
  306. return bitLength / 20 * 64;
  307. }*/
  308. bool primeToCertainty(int certainty, std::mt19937_64& random) {
  309. int rounds = 0;
  310. int n = (std::min(certainty, Integer.MAX_VALUE-1)+1)/2;
  311. // The relationship between the certainty and the number of rounds
  312. // we perform is given in the draft standard ANSI X9.80, "PRIME
  313. // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
  314. int sizeInBits = bitLength();
  315. if (sizeInBits < 100) {
  316. rounds = 50;
  317. rounds = n < rounds ? n : rounds;
  318. return passesMillerRabin(rounds, random);
  319. }
  320. if (sizeInBits < 256) {
  321. rounds = 27;
  322. } else if (sizeInBits < 512) {
  323. rounds = 15;
  324. } else if (sizeInBits < 768) {
  325. rounds = 8;
  326. } else if (sizeInBits < 1024) {
  327. rounds = 4;
  328. } else {
  329. rounds = 2;
  330. }
  331. rounds = n < rounds ? n : rounds;
  332. return passesMillerRabin(rounds, random) && passesLucasLehmer();
  333. }
  334. boolean passesLucasLehmer() {
  335. BigInteger thisPlusOne = this->add(ONE);
  336. // Step 1
  337. int d = 5;
  338. while (jacobiSymbol(d, this) != -1) {
  339. // 5, -7, 9, -11, ...
  340. d = (d < 0) ? std::abs(d)+2 : -(d+2);
  341. }
  342. // Step 2
  343. BigInteger u = lucasLehmerSequence(d, thisPlusOne, *this);
  344. // Step 3
  345. return u.mod(*this).equals(ZERO);
  346. }
  347. static int jacobiSymbol(int p, BigInteger n) {
  348. if (p == 0)
  349. return 0;
  350. // Algorithm and comments adapted from Colin Plumb's C library.
  351. int j = 1;
  352. int u = n.mag[n.mag.length-1];
  353. // Make p positive
  354. if (p < 0) {
  355. p = -p;
  356. int n8 = u & 7;
  357. if ((n8 == 3) || (n8 == 7))
  358. j = -j; // 3 (011) or 7 (111) mod 8
  359. }
  360. // Get rid of factors of 2 in p
  361. while ((p & 3) == 0)
  362. p >>= 2;
  363. if ((p & 1) == 0) {
  364. p >>= 1;
  365. if (((u ^ (u>>1)) & 2) != 0)
  366. j = -j; // 3 (011) or 5 (101) mod 8
  367. }
  368. if (p == 1)
  369. return j;
  370. // Then, apply quadratic reciprocity
  371. if ((p & u & 2) != 0) // p = u = 3 (mod 4)?
  372. j = -j;
  373. // And reduce u mod p
  374. u = n.mod(BigInteger::valueOf(p)).intValue();
  375. // Now compute Jacobi(u,p), u < p
  376. while (u != 0) {
  377. while ((u & 3) == 0)
  378. u >>= 2;
  379. if ((u & 1) == 0) {
  380. u >>= 1;
  381. if (((p ^ (p>>1)) & 2) != 0)
  382. j = -j; // 3 (011) or 5 (101) mod 8
  383. }
  384. if (u == 1)
  385. return j;
  386. // Now both u and p are odd, so use quadratic reciprocity
  387. assert (u < p);
  388. int t = u; u = p; p = t;
  389. if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
  390. j = -j;
  391. // Now u >= p, so it can be reduced
  392. u %= p;
  393. }
  394. return 0;
  395. }
  396. static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
  397. BigInteger d = BigInteger::valueOf(z);
  398. BigInteger u = ONE; BigInteger u2;
  399. BigInteger v = ONE; BigInteger v2;
  400. for (int i=k.bitLength()-2; i >= 0; i--) {
  401. u2 = u.multiply(v).mod(n);
  402. v2 = v.square().add(d.multiply(u.square())).mod(n);
  403. if (v2.testBit(0))
  404. v2 = v2.subtract(n);
  405. v2 = v2.shiftRight(1);
  406. u = u2; v = v2;
  407. if (k.testBit(i)) {
  408. u2 = u.add(v).mod(n);
  409. if (u2.testBit(0))
  410. u2 = u2.subtract(n);
  411. u2 = u2.shiftRight(1);
  412. v2 = v.add(d.multiply(u)).mod(n);
  413. if (v2.testBit(0))
  414. v2 = v2.subtract(n);
  415. v2 = v2.shiftRight(1);
  416. u = u2; v = v2;
  417. }
  418. }
  419. return u;
  420. }
  421. bool passesMillerRabin(int iterations, std::mt19937_64& rnd) {
  422. // Find a and m such that m is odd and this == 1 + 2**a * m
  423. BigInteger thisMinusOne = this->subtract(ONE);
  424. BigInteger m = thisMinusOne;
  425. int a = m.getLowestSetBit();
  426. m = m.shiftRight(a);
  427. // Do the tests
  428. for (int i=0; i < iterations; i++) {
  429. // Generate a uniform random on (1, this)
  430. BigInteger b;
  431. do {
  432. b = BigInteger(this->bitLength(), rnd);
  433. } while (b.compareTo(ONE) <= 0 || b.compareTo(*this) >= 0);
  434. int j = 0;
  435. BigInteger z = b.modPow(m, *this);
  436. while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
  437. if (j > 0 && z.equals(ONE) || ++j == a)
  438. return false;
  439. z = z.modPow(TWO, *this);
  440. }
  441. }
  442. return true;
  443. }
  444. BigInteger(const std::vector<int> magnitude&, int signum) {
  445. this.signum = (magnitude.siz() == 0 ? 0 : signum);
  446. this.mag = magnitude;
  447. if (mag.length >= MAX_MAG_LENGTH) {
  448. checkRange();
  449. }
  450. }
  451. BigInteger(const std::vector<int> magnitude&e, int signum) {
  452. signum = (magnitude.length == 0 ? 0 : signum);
  453. mag = stripLeadingZeroBytes(magnitude);
  454. if (mag.length >= MAX_MAG_LENGTH) {
  455. checkRange();
  456. }
  457. }
  458. void checkRange() {
  459. if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
  460. reportOverflow();
  461. }
  462. }
  463. static void reportOverflow() {
  464. std::cout << "BigInteger would overflow supported range" << std::endl;
  465. throw 1;
  466. }
  467. //Static Factory Methods
  468. static BigInteger valueOf(std::int64_t val) {
  469. // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
  470. if (val == 0)
  471. return ZERO;
  472. if (val > 0 && val <= MAX_CONSTANT)
  473. return posConst[(int) val];
  474. else if (val < 0 && val >= -MAX_CONSTANT)
  475. return negConst[(int) -val];
  476. return BigInteger(val);
  477. }
  478. BigInteger(std::int64_t val) {
  479. if (val < 0) {
  480. val = -val;
  481. signum = -1;
  482. } else {
  483. signum = 1;
  484. }
  485. int highWord = (int)(((uint64_t)val) >> 32);
  486. if (highWord == 0) {
  487. mag = std::vector<int>(1);
  488. mag[0] = (int)val;
  489. } else {
  490. mag = std::vector<int>(2);
  491. mag[0] = highWord;
  492. mag[1] = (int)val;
  493. }
  494. }
  495. static BigInteger valueOf(std::vector<int> val) {
  496. return (val[0] > 0 ? BigInteger(val, 1) : BigInteger(val));
  497. }
  498. // Constants
  499. const static int MAX_CONSTANT = 16;
  500. static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
  501. static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
  502. static volatile BigInteger[][] powerCache;
  503. static const double[] logCache;
  504. static const double LOG_TWO = Math.log(2.0);
  505. static void initStuff(){
  506. for (int i = 1; i <= MAX_CONSTANT; i++) {
  507. std::vector<int> magnitude(1);
  508. magnitude[0] = i;
  509. posConst[i] = BigInteger(magnitude, 1);
  510. negConst[i] = BigInteger(magnitude, -1);
  511. }
  512. /*
  513. * Initialize the cache of radix^(2^x) values used for base conversion
  514. * with just the very first value. Additional values will be created
  515. * on demand.
  516. */
  517. powerCache = new BigInteger[Character.MAX_RADIX+1][];
  518. logCache = new double[Character.MAX_RADIX+1];
  519. for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
  520. powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };
  521. logCache[i] = Math.log(i);
  522. }
  523. }
  524. static const BigInteger ZERO = new BigInteger(std::vector<int>(0), 0);
  525. static const BigInteger ONE = valueOf(1);
  526. static const BigInteger TWO = valueOf(2);
  527. static const BigInteger NEGATIVE_ONE = valueOf(-1);
  528. static const BigInteger TEN = valueOf(10);
  529. // Arithmetic Operations
  530. BigInteger add(BigInteger val) {
  531. if (val.signum == 0)
  532. return *this;
  533. if (signum == 0)
  534. return val;
  535. if (val.signum == signum)
  536. return BigInteger(add(mag, val.mag), signum);
  537. int cmp = compareMagnitude(val);
  538. if (cmp == 0)
  539. return ZERO;
  540. std::vector<int> resultMag = (cmp > 0 ? subtract(mag, val.mag)
  541. : subtract(val.mag, mag));
  542. resultMag = trustedStripLeadingZeroInts(resultMag);
  543. return BigInteger(resultMag, cmp == signum ? 1 : -1);
  544. }
  545. static int signum(std::int64_t a){
  546. if(a == 0)return 0;
  547. if(a > 0)return 1;
  548. return -1;
  549. }
  550. BigInteger add(std::int64_t val) {
  551. if (val == 0)
  552. return *this;
  553. if (signum == 0)
  554. return valueOf(val);
  555. if (signum(val) == signum)
  556. return BigInteger(add(mag, Math.abs(val)), signum);
  557. int cmp = compareMagnitude(val);
  558. if (cmp == 0)
  559. return ZERO;
  560. std::vector<int> resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));
  561. resultMag = trustedStripLeadingZeroInts(resultMag);
  562. return BigInteger(resultMag, cmp == signum ? 1 : -1);
  563. }
  564. static std::vector<int> add(std::vector<int> x, std::uint64_t val) {
  565. std::vector<int> y;
  566. long sum = 0;
  567. int xIndex = x.size();
  568. std::vector<int> result;
  569. int highWord = (int)(val >>> 32);
  570. if (highWord == 0) {
  571. result = std::vector<int>(xIndex);
  572. sum = (x[--xIndex] & LONG_MASK) + val;
  573. result[xIndex] = (int)sum;
  574. } else {
  575. if (xIndex == 1) {
  576. result = std::vector<int>(2);
  577. sum = val + (x[0] & LONG_MASK);
  578. result[1] = (int)sum;
  579. result[0] = (int)(sum >>> 32);
  580. return result;
  581. } else {
  582. result = std::vector<int>(xIndex);
  583. sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);
  584. result[xIndex] = (int)sum;
  585. sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);
  586. result[xIndex] = (int)sum;
  587. }
  588. }
  589. // Copy remainder of longer number while carry propagation is required
  590. bool carry = (sum >>> 32 != 0);
  591. while (xIndex > 0 && carry)
  592. carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
  593. // Copy remainder of longer number
  594. while (xIndex > 0)
  595. result[--xIndex] = x[xIndex];
  596. // Grow result if necessary
  597. if (carry) {
  598. std::vector<int> bigger(result.length + 1);
  599. //System.arraycopy(result, 0, bigger, 1, result.length);
  600. std::copy(result.begin(),result.end(), bigger.begin());
  601. bigger[0] = 0x01;
  602. return bigger;
  603. }
  604. return result;
  605. }
  606. static std::vector<int> add(std::vector<int> x, std::vector<int> y) {
  607. // If x is shorter, swap the two arrays
  608. if (x.size() < y.size()) {
  609. std::swap(x,y);
  610. /*int[] tmp = x;
  611. x = y;
  612. y = tmp;*/
  613. }
  614. int xIndex = x.length;
  615. int yIndex = y.length;
  616. std::vector<int> result(xIndex);// = new int[xIndex];
  617. long sum = 0;
  618. if (yIndex == 1) {
  619. sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
  620. result[xIndex] = (int)sum;
  621. } else {
  622. // Add common parts of both numbers
  623. while (yIndex > 0) {
  624. sum = (x[--xIndex] & LONG_MASK) +
  625. (y[--yIndex] & LONG_MASK) + (sum >>> 32);
  626. result[xIndex] = (int)sum;
  627. }
  628. }
  629. // Copy remainder of longer number while carry propagation is required
  630. boolean carry = (sum >>> 32 != 0);
  631. while (xIndex > 0 && carry)
  632. carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
  633. // Copy remainder of longer number
  634. while (xIndex > 0)
  635. result[--xIndex] = x[xIndex];
  636. // Grow result if necessary
  637. if (carry) {
  638. std::vector<int> bigger(result.length + 1);
  639. std::copy(result.begin(),result.end(),bigger.begin());
  640. bigger[0] = 0x01;
  641. return bigger;
  642. }
  643. return result;
  644. }
  645. static int[] subtract(std::int64_t val, int[] little) {
  646. int highWord = (int)(((uint64_t)val) >> 32);
  647. if (highWord == 0) {
  648. std::vector<int>result(1);
  649. result[0] = (int)(val - (little[0] & LONG_MASK));
  650. return result;
  651. } else {
  652. std::vector<int> result(2);
  653. if (little.length == 1) {
  654. std::int64_t difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);
  655. result[1] = (int)difference;
  656. // Subtract remainder of longer number while borrow propagates
  657. bool borrow = (difference >> 32 != 0);
  658. if (borrow) {
  659. result[0] = highWord - 1;
  660. } else { // Copy remainder of longer number
  661. result[0] = highWord;
  662. }
  663. return result;
  664. } else { // little.length == 2
  665. std::int64_t difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);
  666. result[1] = (int)difference;
  667. difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);
  668. result[0] = (int)difference;
  669. return result;
  670. }
  671. }
  672. }
  673. static std::vector<int> subtract(std::vector<int> big, std::int64_t val) {
  674. int highWord = (int)(((uint64_t)val) >> 32);
  675. int bigIndex = big.size();
  676. std::vector<int> result(bigIndex);
  677. long difference = 0;
  678. if (highWord == 0) {
  679. difference = (big[--bigIndex] & LONG_MASK) - val;
  680. result[bigIndex] = (int)difference;
  681. } else {
  682. difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);
  683. result[bigIndex] = (int)difference;
  684. difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);
  685. result[bigIndex] = (int)difference;
  686. }
  687. // Subtract remainder of longer number while borrow propagates
  688. boolean borrow = (difference >> 32 != 0);
  689. while (bigIndex > 0 && borrow)
  690. borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
  691. // Copy remainder of longer number
  692. while (bigIndex > 0)
  693. result[--bigIndex] = big[bigIndex];
  694. return result;
  695. }
  696. BigInteger subtract(BigInteger val) {
  697. if (val.signum == 0)
  698. return *this;
  699. if (signum == 0)
  700. return val.negate();
  701. if (val.signum != signum)
  702. return BigInteger(add(mag, val.mag), signum);
  703. int cmp = compareMagnitude(val);
  704. if (cmp == 0)
  705. return ZERO;
  706. std::vector<int> resultMag = (cmp > 0 ? subtract(mag, val.mag)
  707. : subtract(val.mag, mag));
  708. resultMag = trustedStripLeadingZeroInts(resultMag);
  709. return BigInteger(resultMag, cmp == signum ? 1 : -1);
  710. }
  711. static std::vector<int> subtract(std::vector<int> big, std::vector<int> little) {
  712. int bigIndex = big.size();
  713. std::vector<int> result(bigIndex);
  714. int littleIndex = little.size();
  715. std::int64_t difference = 0;
  716. // Subtract common parts of both numbers
  717. while (littleIndex > 0) {
  718. difference = (big[--bigIndex] & LONG_MASK) -
  719. (little[--littleIndex] & LONG_MASK) +
  720. (difference >> 32);
  721. result[bigIndex] = (int)difference;
  722. }
  723. // Subtract remainder of longer number while borrow propagates
  724. bool borrow = (difference >> 32 != 0);
  725. while (bigIndex > 0 && borrow)
  726. borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
  727. // Copy remainder of longer number
  728. while (bigIndex > 0)
  729. result[--bigIndex] = big[bigIndex];
  730. return result;
  731. }
  732. BigInteger multiply(BigInteger val) {
  733. if (val.signum == 0 || signum == 0)
  734. return ZERO;
  735. int xlen = mag.size();
  736. if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) {
  737. return square();
  738. }
  739. int ylen = val.mag.size();
  740. if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) {
  741. int resultSign = signum == val.signum ? 1 : -1;
  742. if (val.mag.size() == 1) {
  743. return multiplyByInt(mag,val.mag[0], resultSign);
  744. }
  745. if (mag.size() == 1) {
  746. return multiplyByInt(val.mag,mag[0], resultSign);
  747. }
  748. std::vector<int> result = multiplyToLen(mag, xlen,
  749. val.mag, ylen, null);
  750. result = trustedStripLeadingZeroInts(result);
  751. return BigInteger(result, resultSign);
  752. } else {
  753. if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
  754. return multiplyKaratsuba(this, val);
  755. } else {
  756. return multiplyToomCook3(this, val);
  757. }
  758. }
  759. }
  760. static BigInteger multiplyByInt(std::vector<int> x, int y, int sign) {
  761. if (__builtin_popcount(y) == 1) {
  762. return BigInteger(shiftLeft(x,__builtin_ctz(y)), sign);
  763. }
  764. int xlen = x.length;
  765. std::vector<int> rmag(xlen + 1);
  766. long carry = 0;
  767. long yl = y & LONG_MASK;
  768. int rstart = rmag.length - 1;
  769. for (int i = xlen - 1; i >= 0; i--) {
  770. std::uint64_t product = (x[i] & LONG_MASK) * yl + carry;
  771. rmag[rstart--] = (int)product;
  772. carry = product >> 32;
  773. }
  774. if (carry == 0L) {
  775. rmag.erase(rmag.begin());
  776. } else {
  777. rmag[rstart] = (int)carry;
  778. }
  779. return BigInteger(rmag, sign);
  780. }
  781. BigInteger multiply(std::uint64_t v) {
  782. if (v == 0 || signum == 0)
  783. return ZERO;
  784. if (v == std::numeric_limits<std::uint64_t>::max())
  785. return multiply(BigInteger.valueOf(v));
  786. int rsign = (v > 0 ? signum : -signum);
  787. if (v < 0)
  788. v = -v;
  789. uint64_t dh = v >> 32; // higher order bits
  790. uint64_t dl = v & LONG_MASK; // lower order bits
  791. int xlen = mag.length;
  792. std::vector<int> value = mag;
  793. std::vector<int> rmag = (dh == 0L) ? (std::vector<int>([xlen + 1])) : (std::vector<int>([xlen + 2]));
  794. uint64_t carry = 0;
  795. int rstart = rmag.length - 1;
  796. for (int i = xlen - 1; i >= 0; i--) {
  797. uint64_t product = (value[i] & LONG_MASK) * dl + carry;
  798. rmag[rstart--] = (int)product;
  799. carry = product >> 32;
  800. }
  801. rmag[rstart] = (int)carry;
  802. if (dh != 0L) {
  803. carry = 0;
  804. rstart = rmag.length - 2;
  805. for (int i = xlen - 1; i >= 0; i--) {
  806. long product = (value[i] & LONG_MASK) * dh +
  807. (rmag[rstart] & LONG_MASK) + carry;
  808. rmag[rstart--] = (int)product;
  809. carry = product >> 32;
  810. }
  811. rmag[0] = (int)carry;
  812. }
  813. if (carry == 0LL)
  814. rmag.erase(rmag.begin());
  815. return BigInteger(rmag, rsign);
  816. }
  817. static std::vector<int> multiplyToLen(std::vector<int> x, int xlen, std::vector<int> y, int ylen, std::vector<int> z) {
  818. int xstart = xlen - 1;
  819. int ystart = ylen - 1;
  820. if (z.length < (xlen+ ylen))
  821. z = std::vector<int>(xlen+ylen);
  822. uint64_t carry = 0;
  823. for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
  824. long product = (y[j] & LONG_MASK) *
  825. (x[xstart] & LONG_MASK) + carry;
  826. z[k] = (int)product;
  827. carry = product >> 32;
  828. }
  829. z[xstart] = (int)carry;
  830. for (int i = xstart-1; i >= 0; i--) {
  831. carry = 0;
  832. for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {
  833. long product = (y[j] & LONG_MASK) *
  834. (x[i] & LONG_MASK) +
  835. (z[k] & LONG_MASK) + carry;
  836. z[k] = (int)product;
  837. carry = product >> 32;
  838. }
  839. z[i] = (int)carry;
  840. }
  841. return z;
  842. }
  843. static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
  844. int xlen = x.mag.size();
  845. int ylen = y.mag.size();
  846. // The number of ints in each half of the number.
  847. int half = (std::max(xlen, ylen)+1) / 2;
  848. // xl and yl are the lower halves of x and y respectively,
  849. // xh and yh are the upper halves.
  850. BigInteger xl = x.getLower(half);
  851. BigInteger xh = x.getUpper(half);
  852. BigInteger yl = y.getLower(half);
  853. BigInteger yh = y.getUpper(half);
  854. BigInteger p1 = xh.multiply(yh); // p1 = xh*yh
  855. BigInteger p2 = xl.multiply(yl); // p2 = xl*yl
  856. // p3=(xh+xl)*(yh+yl)
  857. BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
  858. // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
  859. BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
  860. if (x.signum != y.signum) {
  861. return result.negate();
  862. } else {
  863. return result;
  864. }
  865. }
  866. static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
  867. int alen = a.mag.size();
  868. int blen = b.mag.size();
  869. int largest = std::max(alen, blen);
  870. // k is the size (in ints) of the lower-order slices.
  871. int k = (largest+2)/3; // Equal to ceil(largest/3)
  872. // r is the size (in ints) of the highest-order slice.
  873. int r = largest - 2*k;
  874. // Obtain slices of the numbers. a2 and b2 are the most significant
  875. // bits of the numbers a and b, and a0 and b0 the least significant.
  876. BigInteger a0, a1, a2, b0, b1, b2;
  877. a2 = a.getToomSlice(k, r, 0, largest);
  878. a1 = a.getToomSlice(k, r, 1, largest);
  879. a0 = a.getToomSlice(k, r, 2, largest);
  880. b2 = b.getToomSlice(k, r, 0, largest);
  881. b1 = b.getToomSlice(k, r, 1, largest);
  882. b0 = b.getToomSlice(k, r, 2, largest);
  883. BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
  884. v0 = a0.multiply(b0);
  885. da1 = a2.add(a0);
  886. db1 = b2.add(b0);
  887. vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
  888. da1 = da1.add(a1);
  889. db1 = db1.add(b1);
  890. v1 = da1.multiply(db1);
  891. v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
  892. db1.add(b2).shiftLeft(1).subtract(b0));
  893. vinf = a2.multiply(b2);
  894. // The algorithm requires two divisions by 2 and one by 3.
  895. // All divisions are known to be exact, that is, they do not produce
  896. // remainders, and all results are positive. The divisions by 2 are
  897. // implemented as right shifts which are relatively efficient, leaving
  898. // only an exact division by 3, which is done by a specialized
  899. // linear-time algorithm.
  900. t2 = v2.subtract(vm1).exactDivideBy3();
  901. tm1 = v1.subtract(vm1).shiftRight(1);
  902. t1 = v1.subtract(v0);
  903. t2 = t2.subtract(t1).shiftRight(1);
  904. t1 = t1.subtract(tm1).subtract(vinf);
  905. t2 = t2.subtract(vinf.shiftLeft(1));
  906. tm1 = tm1.subtract(t2);
  907. // Number of bits to shift left.
  908. int ss = k*32;
  909. BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
  910. if (a.signum != b.signum) {
  911. return result.negate();
  912. } else {
  913. return result;
  914. }
  915. }
  916. BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
  917. int fullsize) {
  918. int start, end, sliceSize, len, offset;
  919. len = mag.size();
  920. offset = fullsize - len;
  921. if (slice == 0) {
  922. start = 0 - offset;
  923. end = upperSize - 1 - offset;
  924. } else {
  925. start = upperSize + (slice-1)*lowerSize - offset;
  926. end = start + lowerSize - 1;
  927. }
  928. if (start < 0) {
  929. start = 0;
  930. }
  931. if (end < 0) {
  932. return ZERO;
  933. }
  934. sliceSize = (end-start) + 1;
  935. if (sliceSize <= 0) {
  936. return ZERO;
  937. }
  938. // While performing Toom-Cook, all slices are positive and
  939. // the sign is adjusted when the const number is composed.
  940. if (start == 0 && sliceSize >= len) {
  941. return this->abs();
  942. }
  943. std::vector<int> intSlice(sliceSize);
  944. std::copy(mag.begin() + start,mag.begin() + start + sliceSize, intSlice.begin());
  945. return BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
  946. }
  947. BigInteger exactDivideBy3() {
  948. int len = mag.size();
  949. std::vector<int> result(len);
  950. std::int64_t x, w, q, borrow;
  951. borrow = 0L;
  952. for (int i = len-1; i >= 0; i--) {
  953. x = (mag[i] & LONG_MASK);
  954. w = x - borrow;
  955. if (borrow > x) { // Did we make the number go negative?
  956. borrow = 1LL;
  957. } else {
  958. borrow = 0LL;
  959. }
  960. // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus,
  961. // the effect of this is to divide by 3 (mod 2^32).
  962. // This is much faster than division on most architectures.
  963. q = (w * 0xAAAAAAABL) & LONG_MASK;
  964. result[i] = (int) q;
  965. // Now check the borrow. The second check can of course be
  966. // eliminated if the first fails.
  967. if (q >= 0x55555556L) {
  968. borrow++;
  969. if (q >= 0xAAAAAAABL)
  970. borrow++;
  971. }
  972. }
  973. result = trustedStripLeadingZeroInts(result);
  974. return BigInteger(result, signum);
  975. }
  976. BigInteger getLower(int n) {
  977. int len = mag.size();
  978. if (len <= n) {
  979. return abs();
  980. }
  981. std::vector<int>lowerInts(n);
  982. std::copy(mag.begin() + (len - n), mag.end(), lowerInts.begin());
  983. return BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
  984. }
  985. BigInteger getUpper(int n) {
  986. int len = mag.length;
  987. if (len <= n) {
  988. return ZERO;
  989. }
  990. int upperLen = len - n;
  991. std::vector<int> upperInts(upperLen);
  992. std::copy(mag.begin(), mag.begin() + upperLen, upperInts);
  993. return BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
  994. }
  995. // Squaring
  996. BigInteger square() {
  997. if (signum == 0) {
  998. return ZERO;
  999. }
  1000. int len = mag.size();
  1001. if (len < KARATSUBA_SQUARE_THRESHOLD) {
  1002. std::vector<int> z = squareToLen(mag, len, null);
  1003. return BigInteger(trustedStripLeadingZeroInts(z), 1);
  1004. } else {
  1005. if (len < TOOM_COOK_SQUARE_THRESHOLD) {
  1006. return squareKaratsuba();
  1007. } else {
  1008. return squareToomCook3();
  1009. }
  1010. }
  1011. }
  1012. static std::vector<int> squareToLen(std::vector<int> x, int len, std::vector<int> z) {
  1013. int zlen = len << 1;
  1014. if (z == null || z.length < zlen)
  1015. z = std::vector<int>(zlen);
  1016. // Execute checks before calling intrinsified method.
  1017. implSquareToLenChecks(x, len, z, zlen);
  1018. return implSquareToLen(x, len, z, zlen);
  1019. }
  1020. static void implSquareToLenChecks(std::vector<int> x, int len, std::vector<int> z, int zlen){
  1021. if (len < 1) {
  1022. throw std::invalid_argument("invalid input length: " + len);
  1023. }
  1024. if (len > x.size()) {
  1025. throw std::invalid_argument("input length out of bound: " +
  1026. len + " > " + x.size());
  1027. }
  1028. if (len * 2 > z.size()) {
  1029. throw std::invalid_argument("input length out of bound: " +
  1030. (len * 2) + " > " + z.size());
  1031. }
  1032. if (zlen < 1) {
  1033. throw std::invalid_argument("invalid input length: " + zlen);
  1034. }
  1035. if (zlen > z.size()) {
  1036. throw std::invalid_argument("input length out of bound: " +
  1037. len + " > " + z.size());
  1038. }
  1039. }
  1040. static std::vector<int> implSquareToLen(std::vector<int> x, int len, std::vector<int> z, int zlen) {
  1041. /*
  1042. * The algorithm used here is adapted from Colin Plumb's C library.
  1043. * Technique: Consider the partial products in the multiplication
  1044. * of "abcde" by itself:
  1045. *
  1046. * a b c d e
  1047. * * a b c d e
  1048. * ==================
  1049. * ae be ce de ee
  1050. * ad bd cd dd de
  1051. * ac bc cc cd ce
  1052. * ab bb bc bd be
  1053. * aa ab ac ad ae
  1054. *
  1055. * Note that everything above the main diagonal:
  1056. * ae be ce de = (abcd) * e
  1057. * ad bd cd = (abc) * d
  1058. * ac bc = (ab) * c
  1059. * ab = (a) * b
  1060. *
  1061. * is a copy of everything below the main diagonal:
  1062. * de
  1063. * cd ce
  1064. * bc bd be
  1065. * ab ac ad ae
  1066. *
  1067. * Thus, the sum is 2 * (off the diagonal) + diagonal.
  1068. *
  1069. * This is accumulated beginning with the diagonal (which
  1070. * consist of the squares of the digits of the input), which is then
  1071. * divided by two, the off-diagonal added, and multiplied by two
  1072. * again. The low bit is simply a copy of the low bit of the
  1073. * input, so it doesn't need special care.
  1074. */
  1075. // Store the squares, right shifted one bit (i.e., divided by 2)
  1076. int lastProductLowWord = 0;
  1077. for (int j=0, i=0; j < len; j++) {
  1078. std::int64_t piece = (x[j] & LONG_MASK);
  1079. uint64_t product = piece * piece;
  1080. z[i++] = (lastProductLowWord << 31) | (int)(product >> 33);
  1081. z[i++] = (int)(product >> 1);
  1082. lastProductLowWord = (int)product;
  1083. }
  1084. // Add in off-diagonal sums
  1085. for (int i=len, offset=1; i > 0; i--, offset+=2) {
  1086. int t = x[i-1];
  1087. t = mulAdd(z, x, offset, i-1, t);
  1088. addOne(z, offset-1, i, t);
  1089. }
  1090. // Shift back up and set low bit
  1091. primitiveLeftShift(z, zlen, 1);
  1092. z[zlen-1] |= x[len-1] & 1;
  1093. return z;
  1094. }
  1095. BigInteger squareKaratsuba() {
  1096. int half = (mag.size()+1) / 2;
  1097. BigInteger xl = getLower(half);
  1098. BigInteger xh = getUpper(half);
  1099. BigInteger xhs = xh.square(); // xhs = xh^2
  1100. BigInteger xls = xl.square(); // xls = xl^2
  1101. // xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
  1102. return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
  1103. }
  1104. BigInteger squareToomCook3() {
  1105. int len = mag.size();
  1106. // k is the size (in ints) of the lower-order slices.
  1107. int k = (len+2)/3; // Equal to ceil(largest/3)
  1108. // r is the size (in ints) of the highest-order slice.
  1109. int r = len - 2*k;
  1110. // Obtain slices of the numbers. a2 is the most significant
  1111. // bits of the number, and a0 the least significant.
  1112. BigInteger a0, a1, a2;
  1113. a2 = getToomSlice(k, r, 0, len);
  1114. a1 = getToomSlice(k, r, 1, len);
  1115. a0 = getToomSlice(k, r, 2, len);
  1116. BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
  1117. v0 = a0.square();
  1118. da1 = a2.add(a0);
  1119. vm1 = da1.subtract(a1).square();
  1120. da1 = da1.add(a1);
  1121. v1 = da1.square();
  1122. vinf = a2.square();
  1123. v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
  1124. // The algorithm requires two divisions by 2 and one by 3.
  1125. // All divisions are known to be exact, that is, they do not produce
  1126. // remainders, and all results are positive. The divisions by 2 are
  1127. // implemented as right shifts which are relatively efficient, leaving
  1128. // only a division by 3.
  1129. // The division by 3 is done by an optimized algorithm for this case.
  1130. t2 = v2.subtract(vm1).exactDivideBy3();
  1131. tm1 = v1.subtract(vm1).shiftRight(1);
  1132. t1 = v1.subtract(v0);
  1133. t2 = t2.subtract(t1).shiftRight(1);
  1134. t1 = t1.subtract(tm1).subtract(vinf);
  1135. t2 = t2.subtract(vinf.shiftLeft(1));
  1136. tm1 = tm1.subtract(t2);
  1137. // Number of bits to shift left.
  1138. int ss = k*32;
  1139. return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
  1140. }
  1141. // Division
  1142. BigInteger divide(BigInteger val) {
  1143. if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
  1144. mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
  1145. return divideKnuth(val);
  1146. } else {
  1147. return divideBurnikelZiegler(val);
  1148. }
  1149. }
  1150. BigInteger divideKnuth(BigInteger val) {
  1151. MutableBigInteger q = MutableBigInteger(),
  1152. a = MutableBigInteger(this->mag),
  1153. b = MutableBigInteger(val.mag);
  1154. a.divideKnuth(b, q, false);
  1155. return q.toBigInteger(this->signum * val.signum);
  1156. }
  1157. std::vector<BigInteger> divideAndRemainder(BigInteger val) {
  1158. if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
  1159. mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
  1160. return divideAndRemainderKnuth(val);
  1161. } else {
  1162. return divideAndRemainderBurnikelZiegler(val);
  1163. }
  1164. }
  1165. std::vector<BigInteger> divideAndRemainderKnuth(BigInteger val) {
  1166. std::vector<BigInteger> result();
  1167. MutableBigInteger q = MutableBigInteger(),
  1168. a = MutableBigInteger(this->mag),
  1169. b = MutableBigInteger(val.mag);
  1170. MutableBigInteger r = a.divideKnuth(b, q);
  1171. result[0] = q.toBigInteger(this->signum == val.signum ? 1 : -1);
  1172. result[1] = r.toBigInteger(this->signum);
  1173. return result;
  1174. }
  1175. BigInteger remainder(BigInteger val) {
  1176. if (val.mag.size() < BURNIKEL_ZIEGLER_THRESHOLD ||
  1177. mag.size() - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
  1178. return remainderKnuth(val);
  1179. } else {
  1180. return remainderBurnikelZiegler(val);
  1181. }
  1182. }
  1183. BigInteger remainderKnuth(BigInteger val) {
  1184. MutableBigInteger q = MutableBigInteger(),
  1185. a = MutableBigInteger(this->mag),
  1186. b = MutableBigInteger(val.mag);
  1187. return a.divideKnuth(b, q).toBigInteger(this->signum);
  1188. }
  1189. BigInteger divideBurnikelZiegler(BigInteger val) {
  1190. return divideAndRemainderBurnikelZiegler(val)[0];
  1191. }
  1192. BigInteger remainderBurnikelZiegler(BigInteger val) {
  1193. return divideAndRemainderBurnikelZiegler(val)[1];
  1194. }
  1195. std::vector<BigInteger> divideAndRemainderBurnikelZiegler(BigInteger val) {
  1196. MutableBigInteger q = MutableBigInteger();
  1197. MutableBigInteger r = MutableBigInteger(*this).divideAndRemainderBurnikelZiegler(MutableBigInteger(val), q);
  1198. BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);
  1199. BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);
  1200. return std::vector<BigInteger> = {qBigInt, rBigInt};
  1201. }
  1202. BigInteger pow(int exponent) {
  1203. assert(exponent > 0);
  1204. if (signum == 0) {
  1205. return (exponent == 0 ? ONE : this);
  1206. }
  1207. BigInteger partToSquare = this->abs();
  1208. // Factor out powers of two from the base, as the exponentiation of
  1209. // these can be done by left shifts only.
  1210. // The remaining part can then be exponentiated faster. The
  1211. // powers of two will be multiplied back at the end.
  1212. int powersOfTwo = partToSquare.getLowestSetBit();
  1213. long bitsToShift = (std::int64_t)powersOfTwo * exponent;
  1214. if (bitsToShift > std::numeric_limits<int>::max()) {
  1215. reportOverflow();
  1216. }
  1217. int remainingBits;
  1218. // Factor the powers of two out quickly by shifting right, if needed.
  1219. if (powersOfTwo > 0) {
  1220. partToSquare = partToSquare.shiftRight(powersOfTwo);
  1221. remainingBits = partToSquare.bitLength();
  1222. if (remainingBits == 1) { // Nothing left but +/- 1?
  1223. if (signum < 0 && (exponent&1) == 1) {
  1224. return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
  1225. } else {
  1226. return ONE.shiftLeft(powersOfTwo*exponent);
  1227. }
  1228. }
  1229. } else {
  1230. remainingBits = partToSquare.bitLength();
  1231. if (remainingBits == 1) { // Nothing left but +/- 1?
  1232. if (signum < 0 && (exponent&1) == 1) {
  1233. return NEGATIVE_ONE;
  1234. } else {
  1235. return ONE;
  1236. }
  1237. }
  1238. }
  1239. // This is a quick way to approximate the size of the result,
  1240. // similar to doing log2[n] * exponent. This will give an upper bound
  1241. // of how big the result can be, and which algorithm to use.
  1242. long scaleFactor = (long)remainingBits * exponent;
  1243. // Use slightly different algorithms for small and large operands.
  1244. // See if the result will safely fit into a long. (Largest 2^63-1)
  1245. if (partToSquare.mag.size() == 1 && scaleFactor <= 62) {
  1246. // Small number algorithm. Everything fits into a long.
  1247. int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1);
  1248. long result = 1;
  1249. long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
  1250. int workingExponent = exponent;
  1251. // Perform exponentiation using repeated squaring trick
  1252. while (workingExponent != 0) {
  1253. if ((workingExponent & 1) == 1) {
  1254. result = result * baseToPow2;
  1255. }
  1256. if ((workingExponent >>>= 1) != 0) {
  1257. baseToPow2 = baseToPow2 * baseToPow2;
  1258. }
  1259. }
  1260. // Multiply back the powers of two (quickly, by shifting left)
  1261. if (powersOfTwo > 0) {
  1262. if (bitsToShift + scaleFactor <= 62) { // Fits in long?
  1263. return valueOf((result << bitsToShift) * newSign);
  1264. } else {
  1265. return valueOf(result*newSign).shiftLeft((int) bitsToShift);
  1266. }
  1267. }
  1268. else {
  1269. return valueOf(result*newSign);
  1270. }
  1271. } else {
  1272. // Large number algorithm. This is basically identical to
  1273. // the algorithm above, but calls multiply() and square()
  1274. // which may use more efficient algorithms for large numbers.
  1275. BigInteger answer = ONE;
  1276. int workingExponent = exponent;
  1277. // Perform exponentiation using repeated squaring trick
  1278. while (workingExponent != 0) {
  1279. if ((workingExponent & 1) == 1) {
  1280. answer = answer.multiply(partToSquare);
  1281. }
  1282. if ((workingExponent >>>= 1) != 0) {
  1283. partToSquare = partToSquare.square();
  1284. }
  1285. }
  1286. // Multiply back the (exponentiated) powers of two (quickly,
  1287. // by shifting left)
  1288. if (powersOfTwo > 0) {
  1289. answer = answer.shiftLeft(powersOfTwo*exponent);
  1290. }
  1291. if (signum < 0 && (exponent&1) == 1) {
  1292. return answer.negate();
  1293. } else {
  1294. return answer;
  1295. }
  1296. }
  1297. }
  1298. BigInteger gcd(BigInteger val) {
  1299. if (val.signum == 0)
  1300. return this->abs();
  1301. else if (this.signum == 0)
  1302. return val.abs();
  1303. MutableBigInteger a = MutableBigInteger(this);
  1304. MutableBigInteger b = MutableBigInteger(val);
  1305. MutableBigInteger result = a.hybridGCD(b);
  1306. return result.toBigInteger(1);
  1307. }
  1308. static int bitLengthForInt(int n) {
  1309. return 32 - Integer.numberOfLeadingZeros(n);
  1310. }
  1311. static std::vector<int> leftShift(std::vector<int> a, int len, unsigned int n) {
  1312. int nInts = n >> 5;
  1313. int nBits = n&0x1F;
  1314. int bitsInHighWord = bitLengthForInt(a[0]);
  1315. // If shift can be done without recopy, do so
  1316. if (n <= (32 - bitsInHighWord)) {
  1317. primitiveLeftShift(a, len, nBits);
  1318. return a;
  1319. } else { // Array must be resized
  1320. if (nBits <= (32 - bitsInHighWord)) {
  1321. std::vector<int> result(nInts + len);
  1322. std::copy(a.begin(),a.begin() + len, result.begin());
  1323. primitiveLeftShift(result, result.length, nBits);
  1324. return result;
  1325. } else {
  1326. std::vector<int> resul(nInts + len + 1);
  1327. std::copy(a.begin(), a.begin() + len, result.begin());
  1328. primitiveRightShift(result, result.length, 32 - nBits);
  1329. return result;
  1330. }
  1331. }
  1332. }
  1333. // shifts a up to len right n bits assumes no leading zeros, 0<n<32
  1334. static void primitiveRightShift(std::vector<int> a, int len, int n) {
  1335. int n2 = 32 - n;
  1336. for (int i=len-1, c=a[i]; i > 0; i--) {
  1337. unsigned int b = c;
  1338. c = a[i-1];
  1339. a[i] = (c << n2) | (b >> n);
  1340. }
  1341. a[0] = ((unsigned int)a[0]) >> n;
  1342. }
  1343. // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
  1344. static void primitiveLeftShift(std::vector<int> a, int len, int n) {
  1345. if (len == 0 || n == 0)
  1346. return;
  1347. int n2 = 32 - n;
  1348. for (unsigned int i=0, c=a[i], m=i+len-1; i < m; i++) {
  1349. int b = c;
  1350. c = a[i+1];
  1351. a[i] = (b << n) | (c >> n2);
  1352. }
  1353. a[len-1] <<= n;
  1354. }
  1355. static int bitLength(std::vector<int> val, int len) {
  1356. if (len == 0)
  1357. return 0;
  1358. return ((len - 1) << 5) + bitLengthForInt(val[0]);
  1359. }
  1360. BigInteger abs() {
  1361. return (signum >= 0 ? this : this->negate());
  1362. }
  1363. BigInteger negate() {
  1364. return BigInteger(this->mag, -this->signum);
  1365. }
  1366. int signum() {
  1367. return this->signum;
  1368. }
  1369. // Modular Arithmetic Operations
  1370. BigInteger mod(BigInteger m) {
  1371. assert(m.signum > 0)
  1372. BigInteger result = this->remainder(m);
  1373. return (result.signum >= 0 ? result : result.add(m));
  1374. }
  1375. BigInteger modPow(BigInteger exponent, BigInteger m) {
  1376. assert(m.signum > 0)
  1377. // Trivial cases
  1378. if (exponent.signum == 0)
  1379. return (m.equals(ONE) ? ZERO : ONE);
  1380. if (this.equals(ONE))
  1381. return (m.equals(ONE) ? ZERO : ONE);
  1382. if (this.equals(ZERO) && exponent.signum >= 0)
  1383. return ZERO;
  1384. if (this.equals(negConst[1]) && (!exponent.testBit(0)))
  1385. return (m.equals(ONE) ? ZERO : ONE);
  1386. boolean invertResult;
  1387. if ((invertResult = (exponent.signum < 0)))
  1388. exponent = exponent.negate();
  1389. BigInteger base = (this->signum < 0 || this->compareTo(m) >= 0
  1390. ? this->mod(m) : this);
  1391. BigInteger result;
  1392. if (m.testBit(0)) { // odd modulus
  1393. result = base.oddModPow(exponent, m);
  1394. } else {
  1395. /*
  1396. * Even modulus. Tear it into an "odd part" (m1) and power of two
  1397. * (m2), exponentiate mod m1, manually exponentiate mod m2, and
  1398. * use Chinese Remainder Theorem to combine results.
  1399. */
  1400. // Tear m apart into odd part (m1) and power of 2 (m2)
  1401. int p = m.getLowestSetBit(); // Max pow of 2 that divides m
  1402. BigInteger m1 = m.shiftRight(p); // m/2**p
  1403. BigInteger m2 = ONE.shiftLeft(p); // 2**p
  1404. // Calculate new base from m1
  1405. BigInteger base2 = (this->signum < 0 || this->compareTo(m1) >= 0
  1406. ? this->mod(m1) : this);
  1407. // Caculate (base ** exponent) mod m1.
  1408. BigInteger a1 = (m1.equals(ONE) ? ZERO :
  1409. base2.oddModPow(exponent, m1));
  1410. // Calculate (this ** exponent) mod m2
  1411. BigInteger a2 = base.modPow2(exponent, p);
  1412. // Combine results using Chinese Remainder Theorem
  1413. BigInteger y1 = m2.modInverse(m1);
  1414. BigInteger y2 = m1.modInverse(m2);
  1415. if (m.mag.length < MAX_MAG_LENGTH / 2) {
  1416. result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
  1417. } else {
  1418. MutableBigInteger t1;
  1419. new MutableBigInteger(a1.multiply(m2)).multiply(MutableBigInteger(y1), t1);
  1420. MutableBigInteger t2;
  1421. new MutableBigInteger(a2.multiply(m1)).multiply(MutableBigInteger(y2), t2);
  1422. t1.add(t2);
  1423. MutableBigInteger q;
  1424. result = t1.divide(MutableBigInteger(m), q).toBigInteger();
  1425. }
  1426. }
  1427. return (invertResult ? result.modInverse(m) : result);
  1428. }
  1429. // Montgomery multiplication. These are wrappers for
  1430. // implMontgomeryXX routines which are expected to be replaced by
  1431. // virtual machine intrinsics. We don't use the intrinsics for
  1432. // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be
  1433. // larger than any reasonable crypto key.
  1434. static std::vector<int> montgomeryMultiply(std::vector<int> a, std::vector<int> b, std::vector<int> n, int len, long inv,
  1435. std::vector<int> product) {
  1436. implMontgomeryMultiplyChecks(a, b, n, len, product);
  1437. if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
  1438. // Very long argument: do not use an intrinsic
  1439. product = multiplyToLen(a, len, b, len, product);
  1440. return montReduce(product, n, len, (int)inv);
  1441. } else {
  1442. return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));
  1443. }
  1444. }
  1445. static std::vector<int> montgomerySquare(std::vector<int> a, std::vector<int> n, int len, std::int64_t inv,
  1446. std::vector<int> product) {
  1447. implMontgomeryMultiplyChecks(a, a, n, len, product);
  1448. if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
  1449. // Very long argument: do not use an intrinsic
  1450. product = squareToLen(a, len, product);
  1451. return montReduce(product, n, len, (int)inv);
  1452. } else {
  1453. return implMontgomerySquare(a, n, len, inv, materialize(product, len));
  1454. }
  1455. }
  1456. // Range-check everything.
  1457. static void implMontgomeryMultiplyChecks
  1458. (std::vector<int> a, std::vector<int> b, std::vector<int> n, int len, std::vector<int> product) {
  1459. if (len % 2 != 0) {
  1460. throw std::invalid_argument("input array length must be even: " + std::to_string(len));
  1461. }
  1462. if (len < 1) {
  1463. throw std::invalid_argument("invalid input length: " + std::to_string(len));
  1464. }
  1465. if (len > a.size() ||
  1466. len > b.size() ||
  1467. len > n.size() ||
  1468. (len > product.size())) {
  1469. throw std::invalid_argument("input array length out of bound: " + len);
  1470. }
  1471. }
  1472. // Make sure that the int array z (which is expected to contain
  1473. // the result of a Montgomery multiplication) is present and
  1474. // sufficiently large.
  1475. static std::vector<int> materialize(std::vector<int> z, int len) {
  1476. if (z.size() < len)
  1477. z = std::vector<int>(len);
  1478. return z;
  1479. }
  1480. // These methods are intended to be be replaced by virtual machine
  1481. // intrinsics.
  1482. static std::vector<int> implMontgomeryMultiply(std::vector<int> a, std::vector<int> b, std::vector<int> n, int len,
  1483. std::int64_t inv, std::vector<int> product) {
  1484. product = multiplyToLen(a, len, b, len, product);
  1485. return montReduce(product, n, len, (int)inv);
  1486. }
  1487. static std::vector<int> implMontgomerySquare(std::vector<int> a, std::vector<int> n, int len,
  1488. std::int64_t inv, std::vector<int> product) {
  1489. product = squareToLen(a, len, product);
  1490. return montReduce(product, n, len, (int)inv);
  1491. }
  1492. static std::vector<int> bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
  1493. std::numeric_limits<int>::max()}; // Sentinel
  1494. BigInteger oddModPow(BigInteger y, BigInteger z) {
  1495. /*
  1496. * The algorithm is adapted from Colin Plumb's C library.
  1497. *
  1498. * The window algorithm:
  1499. * The idea is to keep a running product of b1 = n^(high-order bits of exp)
  1500. * and then keep appending exponent bits to it. The following patterns
  1501. * apply to a 3-bit window (k = 3):
  1502. * To append 0: square
  1503. * To append 1: square, multiply by n^1
  1504. * To append 10: square, multiply by n^1, square
  1505. * To append 11: square, square, multiply by n^3
  1506. * To append 100: square, multiply by n^1, square, square
  1507. * To append 101: square, square, square, multiply by n^5
  1508. * To append 110: square, square, multiply by n^3, square
  1509. * To append 111: square, square, square, multiply by n^7
  1510. *
  1511. * Since each pattern involves only one multiply, the longer the pattern
  1512. * the better, except that a 0 (no multiplies) can be appended directly.
  1513. * We precompute a table of odd powers of n, up to 2^k, and can then
  1514. * multiply k bits of exponent at a time. Actually, assuming random
  1515. * exponents, there is on average one zero bit between needs to
  1516. * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
  1517. * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
  1518. * you have to do one multiply per k+1 bits of exponent.
  1519. *
  1520. * The loop walks down the exponent, squaring the result buffer as
  1521. * it goes. There is a wbits+1 bit lookahead buffer, buf, that is
  1522. * filled with the upcoming exponent bits. (What is read after the
  1523. * end of the exponent is unimportant, but it is filled with zero here.)
  1524. * When the most-significant bit of this buffer becomes set, i.e.
  1525. * (buf & tblmask) != 0, we have to decide what pattern to multiply
  1526. * by, and when to do it. We decide, remember to do it in future
  1527. * after a suitable number of squarings have passed (e.g. a pattern
  1528. * of "100" in the buffer requires that we multiply by n^1 immediately;
  1529. * a pattern of "110" calls for multiplying by n^3 after one more
  1530. * squaring), clear the buffer, and continue.
  1531. *
  1532. * When we start, there is one more optimization: the result buffer
  1533. * is implcitly one, so squaring it or multiplying by it can be
  1534. * optimized away. Further, if we start with a pattern like "100"
  1535. * in the lookahead window, rather than placing n into the buffer
  1536. * and then starting to square it, we have already computed n^2
  1537. * to compute the odd-powers table, so we can place that into
  1538. * the buffer and save a squaring.
  1539. *
  1540. * This means that if you have a k-bit window, to compute n^z,
  1541. * where z is the high k bits of the exponent, 1/2 of the time
  1542. * it requires no squarings. 1/4 of the time, it requires 1
  1543. * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
  1544. * And the remaining 1/2^(k-1) of the time, the top k bits are a
  1545. * 1 followed by k-1 0 bits, so it again only requires k-2
  1546. * squarings, not k-1. The average of these is 1. Add that
  1547. * to the one squaring we have to do to compute the table,
  1548. * and you'll see that a k-bit window saves k-2 squarings
  1549. * as well as reducing the multiplies. (It actually doesn't
  1550. * hurt in the case k = 1, either.)
  1551. */
  1552. // Special case for exponent of one
  1553. if (y.equals(ONE))
  1554. return *this;
  1555. // Special case for base of zero
  1556. if (signum == 0)
  1557. return ZERO;
  1558. std::vector<int> base = mag.clone();
  1559. std::vector<int> exp = y.mag;
  1560. std::vector<int> mod = z.mag;
  1561. int modLen = mod.size();
  1562. // Make modLen even. It is conventional to use a cryptographic
  1563. // modulus that is 512, 768, 1024, or 2048 bits, so this code
  1564. // will not normally be executed. However, it is necessary for
  1565. // the correct functioning of the HotSpot intrinsics.
  1566. if ((modLen & 1) != 0) {
  1567. std::vector<int> x(modlen + 1);
  1568. std::copy(mod.begin(), mod.begin() + modLen, x.begin());
  1569. mod = std::move(x);
  1570. modLen++;
  1571. }
  1572. // Select an appropriate window size
  1573. int wbits = 0;
  1574. int ebits = bitLength(exp, exp.size());
  1575. // if exponent is 65537 (0x10001), use minimum window size
  1576. if ((ebits != 17) || (exp[0] != 65537)) {
  1577. while (ebits > bnExpModThreshTable[wbits]) {
  1578. wbits++;
  1579. }
  1580. }
  1581. // Calculate appropriate table size
  1582. int tblmask = 1 << wbits;
  1583. // Allocate table for precomputed odd powers of base in Montgomery form
  1584. std::vector<std::vector<int>> table(tblmask);// = new int[tblmask][];
  1585. for (int i=0; i < tblmask; i++)
  1586. table[i] = std::vector<int>(modLen);
  1587. // Compute the modular inverse of the least significant 64-bit
  1588. // digit of the modulus
  1589. std::int64_t n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);
  1590. std::int64_t inv = -MutableBigInteger.inverseMod64(n0);
  1591. // Convert base to Montgomery form
  1592. std::vector<int> a = leftShift(base, base.length, modLen << 5);
  1593. MutableBigInteger q = MutableBigInteger(),
  1594. a2 = MutableBigInteger(a),
  1595. b2 = MutableBigInteger(mod);
  1596. b2.normalize(); // MutableBigInteger.divide() assumes that its
  1597. // divisor is in normal form.
  1598. MutableBigInteger r= a2.divide(b2, q);
  1599. table[0] = r.toIntArray();
  1600. // Pad table[0] with leading zeros so its length is at least modLen
  1601. if (table[0].size() < modLen) {
  1602. int offset = modLen - table[0].size();
  1603. std::vector<int> t2(modLen);// = new int[modLen];
  1604. std::copy(table[0].begin(),table[0].end(), t2.begin());
  1605. table[0] = t2;
  1606. }
  1607. // Set b to the square of the base
  1608. std::vector<int> b = montgomerySquare(table[0], mod, modLen, inv, null);
  1609. // Set t to high half of b
  1610. std::vector<int> t(b.begin(), b.begin() + modLen);
  1611. // Fill in the table with odd powers of the base
  1612. for (int i=1; i < tblmask; i++) {
  1613. table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);
  1614. }
  1615. // Pre load the window that slides over the exponent
  1616. unsigned int bitpos = 1 << ((ebits-1) & (32-1));
  1617. int buf = 0;
  1618. int elen = exp.length;
  1619. int eIndex = 0;
  1620. for (int i = 0; i <= wbits; i++) {
  1621. buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
  1622. bitpos >>>= 1;
  1623. if (bitpos == 0) {
  1624. eIndex++;
  1625. bitpos = 1 << (32-1);
  1626. elen--;
  1627. }
  1628. }
  1629. int multpos = ebits;
  1630. // The first iteration, which is hoisted out of the main loop
  1631. ebits--;
  1632. boolean isone = true;
  1633. multpos = ebits - wbits;
  1634. while ((buf & 1) == 0) {
  1635. buf >>>= 1;
  1636. multpos++;
  1637. }
  1638. int[] mult = table[buf >>> 1];
  1639. buf = 0;
  1640. if (multpos == ebits)
  1641. isone = false;
  1642. // The main loop
  1643. while (true) {
  1644. ebits--;
  1645. // Advance the window
  1646. buf <<= 1;
  1647. if (elen != 0) {
  1648. buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
  1649. bitpos >>>= 1;
  1650. if (bitpos == 0) {
  1651. eIndex++;
  1652. bitpos = 1 << (32-1);
  1653. elen--;
  1654. }
  1655. }
  1656. // Examine the window for pending multiplies
  1657. if ((buf & tblmask) != 0) {
  1658. multpos = ebits - wbits;
  1659. while ((buf & 1) == 0) {
  1660. buf >>>= 1;
  1661. multpos++;
  1662. }
  1663. mult = table[buf >>> 1];
  1664. buf = 0;
  1665. }
  1666. // Perform multiply
  1667. if (ebits == multpos) {
  1668. if (isone) {
  1669. b = mult.clone();
  1670. isone = false;
  1671. } else {
  1672. t = b;
  1673. a = montgomeryMultiply(t, mult, mod, modLen, inv, a);
  1674. t = a; a = b; b = t;
  1675. }
  1676. }
  1677. // Check if done
  1678. if (ebits == 0)
  1679. break;
  1680. // Square the input
  1681. if (!isone) {
  1682. t = b;
  1683. a = montgomerySquare(t, mod, modLen, inv, a);
  1684. t = a; a = b; b = t;
  1685. }
  1686. }
  1687. // Convert result out of Montgomery form and return
  1688. int[] t2 = new int[2*modLen];
  1689. System.arraycopy(b, 0, t2, modLen, modLen);
  1690. b = montReduce(t2, mod, modLen, (int)inv);
  1691. t2 = Arrays.copyOf(b, modLen);
  1692. return new BigInteger(1, t2);
  1693. }
  1694. static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
  1695. int c=0;
  1696. int len = mlen;
  1697. int offset=0;
  1698. do {
  1699. int nEnd = n[n.length-1-offset];
  1700. int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
  1701. c += addOne(n, offset, mlen, carry);
  1702. offset++;
  1703. } while (--len > 0);
  1704. while (c > 0)
  1705. c += subN(n, mod, mlen);
  1706. while (intArrayCmpToLen(n, mod, mlen) >= 0)
  1707. subN(n, mod, mlen);
  1708. return n;
  1709. }
  1710. /*
  1711. * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
  1712. * equal to, or greater than arg2 up to length len.
  1713. */
  1714. static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
  1715. for (int i=0; i < len; i++) {
  1716. long b1 = arg1[i] & LONG_MASK;
  1717. long b2 = arg2[i] & LONG_MASK;
  1718. if (b1 < b2)
  1719. return -1;
  1720. if (b1 > b2)
  1721. return 1;
  1722. }
  1723. return 0;
  1724. }
  1725. static int subN(int[] a, int[] b, int len) {
  1726. long sum = 0;
  1727. while (--len >= 0) {
  1728. sum = (a[len] & LONG_MASK) -
  1729. (b[len] & LONG_MASK) + (sum >> 32);
  1730. a[len] = (int)sum;
  1731. }
  1732. return (int)(sum >> 32);
  1733. }
  1734. static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
  1735. implMulAddCheck(out, in, offset, len, k);
  1736. return implMulAdd(out, in, offset, len, k);
  1737. }
  1738. static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {
  1739. if (len > in.length) {
  1740. throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);
  1741. }
  1742. if (offset < 0) {
  1743. throw new IllegalArgumentException("input offset is invalid: " + offset);
  1744. }
  1745. if (offset > (out.length - 1)) {
  1746. throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));
  1747. }
  1748. if (len > (out.length - offset)) {
  1749. throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));
  1750. }
  1751. }
  1752. static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {
  1753. long kLong = k & LONG_MASK;
  1754. long carry = 0;
  1755. offset = out.length-offset - 1;
  1756. for (int j=len-1; j >= 0; j--) {
  1757. long product = (in[j] & LONG_MASK) * kLong +
  1758. (out[offset] & LONG_MASK) + carry;
  1759. out[offset--] = (int)product;
  1760. carry = product >>> 32;
  1761. }
  1762. return (int)carry;
  1763. }
  1764. static int addOne(int[] a, int offset, int mlen, int carry) {
  1765. offset = a.length-1-mlen-offset;
  1766. long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
  1767. a[offset] = (int)t;
  1768. if ((t >>> 32) == 0)
  1769. return 0;
  1770. while (--mlen >= 0) {
  1771. if (--offset < 0) { // Carry out of number
  1772. return 1;
  1773. } else {
  1774. a[offset]++;
  1775. if (a[offset] != 0)
  1776. return 0;
  1777. }
  1778. }
  1779. return 1;
  1780. }
  1781. BigInteger modPow2(BigInteger exponent, int p) {
  1782. /*
  1783. * Perform exponentiation using repeated squaring trick, chopping off
  1784. * high order bits as indicated by modulus.
  1785. */
  1786. BigInteger result = ONE;
  1787. BigInteger baseToPow2 = this.mod2(p);
  1788. int expOffset = 0;
  1789. int limit = exponent.bitLength();
  1790. if (this.testBit(0))
  1791. limit = (p-1) < limit ? (p-1) : limit;
  1792. while (expOffset < limit) {
  1793. if (exponent.testBit(expOffset))
  1794. result = result.multiply(baseToPow2).mod2(p);
  1795. expOffset++;
  1796. if (expOffset < limit)
  1797. baseToPow2 = baseToPow2.square().mod2(p);
  1798. }
  1799. return result;
  1800. }
  1801. BigInteger mod2(int p) {
  1802. if (bitLength() <= p)
  1803. return this;
  1804. // Copy remaining ints of mag
  1805. int numInts = (p + 31) >>> 5;
  1806. int[] mag = new int[numInts];
  1807. System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);
  1808. // Mask out any excess bits
  1809. int excessBits = (numInts << 5) - p;
  1810. mag[0] &= (1L << (32-excessBits)) - 1;
  1811. return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
  1812. }
  1813. BigInteger modInverse(BigInteger m) {
  1814. if (m.signum != 1)
  1815. throw new ArithmeticException("BigInteger: modulus not positive");
  1816. if (m.equals(ONE))
  1817. return ZERO;
  1818. // Calculate (this mod m)
  1819. BigInteger modVal = this;
  1820. if (signum < 0 || (this.compareMagnitude(m) >= 0))
  1821. modVal = this.mod(m);
  1822. if (modVal.equals(ONE))
  1823. return ONE;
  1824. MutableBigInteger a = new MutableBigInteger(modVal);
  1825. MutableBigInteger b = new MutableBigInteger(m);
  1826. MutableBigInteger result = a.mutableModInverse(b);
  1827. return result.toBigInteger(1);
  1828. }
  1829. // Shift Operations
  1830. BigInteger shiftLeft(int n) {
  1831. if (signum == 0)
  1832. return ZERO;
  1833. if (n > 0) {
  1834. return new BigInteger(shiftLeft(mag, n), signum);
  1835. } else if (n == 0) {
  1836. return this;
  1837. } else {
  1838. // Possible int overflow in (-n) is not a trouble,
  1839. // because shiftRightImpl considers its argument unsigned
  1840. return shiftRightImpl(-n);
  1841. }
  1842. }
  1843. static int[] shiftLeft(int[] mag, int n) {
  1844. int nInts = n >>> 5;
  1845. int nBits = n & 0x1f;
  1846. int magLen = mag.length;
  1847. int newMag[] = null;
  1848. if (nBits == 0) {
  1849. newMag = new int[magLen + nInts];
  1850. System.arraycopy(mag, 0, newMag, 0, magLen);
  1851. } else {
  1852. int i = 0;
  1853. int nBits2 = 32 - nBits;
  1854. int highBits = mag[0] >>> nBits2;
  1855. if (highBits != 0) {
  1856. newMag = new int[magLen + nInts + 1];
  1857. newMag[i++] = highBits;
  1858. } else {
  1859. newMag = new int[magLen + nInts];
  1860. }
  1861. int j=0;
  1862. while (j < magLen-1)
  1863. newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
  1864. newMag[i] = mag[j] << nBits;
  1865. }
  1866. return newMag;
  1867. }
  1868. BigInteger shiftRight(int n) {
  1869. if (signum == 0)
  1870. return ZERO;
  1871. if (n > 0) {
  1872. return shiftRightImpl(n);
  1873. } else if (n == 0) {
  1874. return this;
  1875. } else {
  1876. return BigInteger(shiftLeft(mag, -n), signum);
  1877. }
  1878. }
  1879. BigInteger shiftRightImpl(int n) {
  1880. int nInts = n >>> 5;
  1881. int nBits = n & 0x1f;
  1882. int magLen = mag.length;
  1883. int newMag[] = null;
  1884. // Special case: entire contents shifted off the end
  1885. if (nInts >= magLen)
  1886. return (signum >= 0 ? ZERO : negConst[1]);
  1887. if (nBits == 0) {
  1888. int newMagLen = magLen - nInts;
  1889. newMag = Arrays.copyOf(mag, newMagLen);
  1890. } else {
  1891. int i = 0;
  1892. int highBits = mag[0] >>> nBits;
  1893. if (highBits != 0) {
  1894. newMag = new int[magLen - nInts];
  1895. newMag[i++] = highBits;
  1896. } else {
  1897. newMag = new int[magLen - nInts -1];
  1898. }
  1899. int nBits2 = 32 - nBits;
  1900. int j=0;
  1901. while (j < magLen - nInts - 1)
  1902. newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
  1903. }
  1904. if (signum < 0) {
  1905. // Find out whether any one-bits were shifted off the end.
  1906. boolean onesLost = false;
  1907. for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
  1908. onesLost = (mag[i] != 0);
  1909. if (!onesLost && nBits != 0)
  1910. onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
  1911. if (onesLost)
  1912. newMag = javaIncrement(newMag);
  1913. }
  1914. return new BigInteger(newMag, signum);
  1915. }
  1916. int[] javaIncrement(int[] val) {
  1917. int lastSum = 0;
  1918. for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
  1919. lastSum = (val[i] += 1);
  1920. if (lastSum == 0) {
  1921. val = new int[val.length+1];
  1922. val[0] = 1;
  1923. }
  1924. return val;
  1925. }
  1926. // Bitwise Operations
  1927. BigInteger and(BigInteger val) {
  1928. int[] result = new int[Math.max(intLength(), val.intLength())];
  1929. for (int i=0; i < result.length; i++)
  1930. result[i] = (getInt(result.length-i-1)
  1931. & val.getInt(result.length-i-1));
  1932. return valueOf(result);
  1933. }
  1934. BigInteger or(BigInteger val) {
  1935. int[] result = new int[Math.max(intLength(), val.intLength())];
  1936. for (int i=0; i < result.length; i++)
  1937. result[i] = (getInt(result.length-i-1)
  1938. | val.getInt(result.length-i-1));
  1939. return valueOf(result);
  1940. }
  1941. BigInteger xor(BigInteger val) {
  1942. int[] result = new int[Math.max(intLength(), val.intLength())];
  1943. for (int i=0; i < result.length; i++)
  1944. result[i] = (getInt(result.length-i-1)
  1945. ^ val.getInt(result.length-i-1));
  1946. return valueOf(result);
  1947. }
  1948. BigInteger not() {
  1949. int[] result = new int[intLength()];
  1950. for (int i=0; i < result.length; i++)
  1951. result[i] = ~getInt(result.length-i-1);
  1952. return valueOf(result);
  1953. }
  1954. BigInteger andNot(BigInteger val) {
  1955. int[] result = new int[Math.max(intLength(), val.intLength())];
  1956. for (int i=0; i < result.length; i++)
  1957. result[i] = (getInt(result.length-i-1)
  1958. & ~val.getInt(result.length-i-1));
  1959. return valueOf(result);
  1960. }
  1961. // Single Bit Operations
  1962. boolean testBit(int n) {
  1963. if (n < 0)
  1964. throw new ArithmeticException("Negative bit address");
  1965. return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
  1966. }
  1967. BigInteger setBit(int n) {
  1968. if (n < 0)
  1969. throw new ArithmeticException("Negative bit address");
  1970. int intNum = n >>> 5;
  1971. int[] result = new int[Math.max(intLength(), intNum+2)];
  1972. for (int i=0; i < result.length; i++)
  1973. result[result.length-i-1] = getInt(i);
  1974. result[result.length-intNum-1] |= (1 << (n & 31));
  1975. return valueOf(result);
  1976. }
  1977. BigInteger clearBit(int n) {
  1978. if (n < 0)
  1979. throw new ArithmeticException("Negative bit address");
  1980. int intNum = n >>> 5;
  1981. int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
  1982. for (int i=0; i < result.length; i++)
  1983. result[result.length-i-1] = getInt(i);
  1984. result[result.length-intNum-1] &= ~(1 << (n & 31));
  1985. return valueOf(result);
  1986. }
  1987. BigInteger flipBit(int n) {
  1988. if (n < 0)
  1989. throw new ArithmeticException("Negative bit address");
  1990. int intNum = n >>> 5;
  1991. int[] result = new int[Math.max(intLength(), intNum+2)];
  1992. for (int i=0; i < result.length; i++)
  1993. result[result.length-i-1] = getInt(i);
  1994. result[result.length-intNum-1] ^= (1 << (n & 31));
  1995. return valueOf(result);
  1996. }
  1997. int getLowestSetBit() {
  1998. if (lsb == -2) { // lowestSetBit not initialized yet
  1999. lsb = 0;
  2000. if (signum == 0) {
  2001. lsb -= 1;
  2002. } else {
  2003. // Search for lowest order nonzero int
  2004. int i,b;
  2005. for (i=0; (b = getInt(i)) == 0; i++)
  2006. ;
  2007. lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
  2008. }
  2009. lowestSetBit = lsb + 2;
  2010. }
  2011. return lsb;
  2012. }
  2013. // Miscellaneous Bit Operations
  2014. int bitLength() {
  2015. if (n == -1) { // bitLength not initialized yet
  2016. int[] m = mag;
  2017. int len = m.length;
  2018. if (len == 0) {
  2019. n = 0; // offset by one to initialize
  2020. } else {
  2021. // Calculate the bit length of the magnitude
  2022. int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
  2023. if (signum < 0) {
  2024. // Check if magnitude is a power of two
  2025. boolean pow2 = (Integer.bitCount(mag[0]) == 1);
  2026. for (int i=1; i< len && pow2; i++)
  2027. pow2 = (mag[i] == 0);
  2028. n = (pow2 ? magBitLength -1 : magBitLength);
  2029. } else {
  2030. n = magBitLength;
  2031. }
  2032. }
  2033. bitLength = n + 1;
  2034. }
  2035. return n;
  2036. }
  2037. int bitCount() {
  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. }