BigInteger.cpp 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203
  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. unsigned int buf = 0;
  1618. int elen = exp.size();
  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. bool isone = true;
  1633. multpos = ebits - wbits;
  1634. while ((buf & 1) == 0) {
  1635. buf >>= 1;
  1636. multpos++;
  1637. }
  1638. std::vector<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;
  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. std::vector<int> t2(2 * modLen);
  1689. std::copy(b.begin(), b.begin() + modLen, t2.begin() + modLen);
  1690. b = montReduce(t2, mod, modLen, (int)inv);
  1691. t2 = std::vector<int>(b.begin(),b.begin() + modLen);
  1692. return BigInteger(1, t2);
  1693. }
  1694. static std::vector<int> montReduce(std::vector<int> n, std::vector<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(std::vector<int> arg1, std::vector<int> arg2, int len) {
  1715. for (int i=0; i < len; i++) {
  1716. std::int64_t b1 = arg1[i] & LONG_MASK;
  1717. std::int64_t 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(std::vector<int> a, std::vector<int> b, int len) {
  1726. std::int64_t 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(std::vector<int> out, std::vector<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(std::vector<int> out, std::vector<int> in, int offset, int len, int k) {
  1739. if (len > in.size()) {
  1740. throw std::invalid_argument("input length is out of bound: " + std::to_string(len) + " > " + std::to_string(in.size()));
  1741. }
  1742. if (offset < 0) {
  1743. throw std::invalid_argument("input offset is invalid: " + std::to_string(offset));
  1744. }
  1745. if (offset > (out.length - 1)) {
  1746. throw std::invalid_argument("input offset is out of bound: " + std::to_string(offset) + " > " + std::to_string(out.length - 1));
  1747. }
  1748. if (len > (out.length - offset)) {
  1749. throw std::invalid_argument("input len is out of bound: " + std::to_string(len) + " > " + std::to_string(out.length - offset));
  1750. }
  1751. }
  1752. static int implMulAdd(std::vector<int> out, std::vector<int> in, int offset, int len, int k) {
  1753. std::int64_t kLong = k & LONG_MASK;
  1754. std::int64_t carry = 0;
  1755. offset = out.length-offset - 1;
  1756. for (int j=len-1; j >= 0; j--) {
  1757. std::uint64_t 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(std::vector<int> a, int offset, int mlen, int carry) {
  1765. offset = a.length-1-mlen-offset;
  1766. std::uint64_t 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(unsigned int p) {
  1802. if (bitLength() <= p)
  1803. return this;
  1804. // Copy remaining ints of mag
  1805. int numInts = (p + 31) >> 5;
  1806. std::vector<int> mag(numInts,0);
  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] &= (1LL << (32-excessBits)) - 1;
  1811. return (mag[0] == 0 ? BigInteger(1, mag) : BigInteger(mag, 1));
  1812. }
  1813. BigInteger modInverse(BigInteger m) {
  1814. assert (m.signum == 1);
  1815. if (m.equals(ONE))
  1816. return ZERO;
  1817. // Calculate (this mod m)
  1818. BigInteger modVal = *this;
  1819. if (signum < 0 || (this->compareMagnitude(m) >= 0))
  1820. modVal = this->mod(m);
  1821. if (modVal.equals(ONE))
  1822. return ONE;
  1823. MutableBigInteger a = MutableBigInteger(modVal);
  1824. MutableBigInteger b = MutableBigInteger(m);
  1825. MutableBigInteger result = a.mutableModInverse(b);
  1826. return result.toBigInteger(1);
  1827. }
  1828. // Shift Operations
  1829. BigInteger shiftLeft(int n) {
  1830. if (signum == 0)
  1831. return ZERO;
  1832. if (n > 0) {
  1833. return BigInteger(shiftLeft(mag, n), signum);
  1834. } else if (n == 0) {
  1835. return *this;
  1836. } else {
  1837. // Possible int overflow in (-n) is not a trouble,
  1838. // because shiftRightImpl considers its argument unsigned
  1839. return shiftRightImpl(-n);
  1840. }
  1841. }
  1842. static std::vector<int> shiftLeft(std::vector<int> mag, unsigned int n) {
  1843. int nInts = n >> 5;
  1844. int nBits = n & 0x1f;
  1845. int magLen = mag.size();
  1846. std::vector<int> newMag;
  1847. if (nBits == 0) {
  1848. newMag = std::vector<int>(magLen + nInts);
  1849. System.arraycopy(mag.begin(), mag.end(), newMag.begin());
  1850. } else {
  1851. int i = 0;
  1852. int nBits2 = 32 - nBits;
  1853. int highBits = ((unsigned int)mag[0]) >> nBits2;
  1854. if (highBits != 0) {
  1855. newMag = std::vector<int>([magLen + nInts + 1]);
  1856. newMag[i++] = highBits;
  1857. } else {
  1858. newMag = std::vector<int>(magLen + nInts);
  1859. }
  1860. int j=0;
  1861. while (j < magLen-1)
  1862. newMag[i++] = mag[j++] << nBits | ((unsigned int)mag[j]) >> nBits2;
  1863. newMag[i] = mag[j] << nBits;
  1864. }
  1865. return newMag;
  1866. }
  1867. BigInteger shiftRight(int n) {
  1868. if (signum == 0)
  1869. return ZERO;
  1870. if (n > 0) {
  1871. return shiftRightImpl(n);
  1872. } else if (n == 0) {
  1873. return this;
  1874. } else {
  1875. return BigInteger(shiftLeft(mag, -n), signum);
  1876. }
  1877. }
  1878. BigInteger shiftRightImpl(unsigned int n) {
  1879. int nInts = n >> 5;
  1880. int nBits = n & 0x1f;
  1881. int magLen = mag.size();
  1882. std::vector<int> newMag;
  1883. // Special case: entire contents shifted off the end
  1884. if (nInts >= magLen)
  1885. return (signum >= 0 ? ZERO : negConst[1]);
  1886. if (nBits == 0) {
  1887. int newMagLen = magLen - nInts;
  1888. newMag = std::vector<int>(mag.begin(), mag.begin() + newMagLen);
  1889. } else {
  1890. int i = 0;
  1891. int highBits = ((unsigned int)mag[0]) >> nBits;
  1892. if (highBits != 0) {
  1893. newMag = std::vector<int>(magLen - nInts);
  1894. newMag[i++] = highBits;
  1895. } else {
  1896. newMag = std::vector<int>(magLen - nInts - 1);
  1897. }
  1898. int nBits2 = 32 - nBits;
  1899. int j=0;
  1900. while (j < magLen - nInts - 1)
  1901. newMag[i++] = (mag[j++] << nBits2) | (((unsigned int)mag[j]) >> nBits);
  1902. }
  1903. if (signum < 0) {
  1904. // Find out whether any one-bits were shifted off the end.
  1905. bool onesLost = false;
  1906. for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
  1907. onesLost = (mag[i] != 0);
  1908. if (!onesLost && nBits != 0)
  1909. onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
  1910. if (onesLost)
  1911. newMag = javaIncrement(newMag);
  1912. }
  1913. return BigInteger(newMag, signum);
  1914. }
  1915. std::vector<int> javaIncrement(std::vector<int> val) {
  1916. int lastSum = 0;
  1917. for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
  1918. lastSum = (val[i] += 1);
  1919. if (lastSum == 0) {
  1920. val = std::vector<int>(val.length+1);
  1921. val[0] = 1;
  1922. }
  1923. return val;
  1924. }
  1925. // Bitwise Operations
  1926. BigInteger and(BigInteger val) {
  1927. std::vector<int> result(std::max(intLength(), val.intLength()));
  1928. for (int i=0; i < result.length; i++)
  1929. result[i] = (getInt(result.length-i-1)
  1930. & val.getInt(result.length-i-1));
  1931. return valueOf(result);
  1932. }
  1933. BigInteger or(BigInteger val) {
  1934. std::vector<int> result(std::max(intLength(), val.intLength()));
  1935. for (int i=0; i < result.length; i++)
  1936. result[i] = (getInt(result.length-i-1)
  1937. | val.getInt(result.length-i-1));
  1938. return valueOf(result);
  1939. }
  1940. BigInteger xor(BigInteger val) {
  1941. std::vector<int> result(std::max(intLength(), val.intLength()));
  1942. for (int i=0; i < result.length; i++)
  1943. result[i] = (getInt(result.length-i-1)
  1944. ^ val.getInt(result.length-i-1));
  1945. return valueOf(result);
  1946. }
  1947. BigInteger not() {
  1948. std::vector<int> result(intLength());
  1949. for (int i=0; i < result.length; i++)
  1950. result[i] = ~getInt(result.length-i-1);
  1951. return valueOf(result);
  1952. }
  1953. BigInteger andNot(BigInteger val) {
  1954. std::vector<int> result(std::max(intLength(), val.intLength()));
  1955. for (int i=0; i < result.length; i++)
  1956. result[i] = (getInt(result.length-i-1)
  1957. & ~val.getInt(result.length-i-1));
  1958. return valueOf(result);
  1959. }
  1960. // Single Bit Operations
  1961. bool testBit(unsigned int n) {
  1962. return (getInt(n >> 5) & (1 << (n & 31))) != 0;
  1963. }
  1964. BigInteger setBit(unsigned int n) {
  1965. int intNum = n >>> 5;
  1966. std::vector<int> result(std::max(intLength(), intNum+2));
  1967. for (int i=0; i < result.length; i++)
  1968. result[result.length-i-1] = getInt(i);
  1969. result[result.length-intNum-1] |= (1 << (n & 31));
  1970. return valueOf(result);
  1971. }
  1972. BigInteger clearBit(unsigned int n) {
  1973. int intNum = n >> 5;
  1974. std::vector<int> result(std::max(intLength(), ((n + 1) >> 5) + 1));
  1975. for (int i=0; i < result.length; i++)
  1976. result[result.length-i-1] = getInt(i);
  1977. result[result.length-intNum-1] &= ~(1 << (n & 31));
  1978. return valueOf(result);
  1979. }
  1980. BigInteger flipBit(unsigned int n) {
  1981. int intNum = n >> 5;
  1982. std::vector<int> result(std::max(intLength(), intNum+2));
  1983. for (int i=0; i < result.length; i++)
  1984. result[result.length-i-1] = getInt(i);
  1985. result[result.length-intNum-1] ^= (1 << (n & 31));
  1986. return valueOf(result);
  1987. }
  1988. int getLowestSetBit() {
  1989. if (lsb == -2) { // lowestSetBit not initialized yet
  1990. lsb = 0;
  1991. if (signum == 0) {
  1992. lsb -= 1;
  1993. } else {
  1994. // Search for lowest order nonzero int
  1995. int i,b;
  1996. for (i=0; (b = getInt(i)) == 0; i++)
  1997. ;
  1998. lsb += (i << 5) + __builtin_ctz(b);
  1999. }
  2000. lowestSetBit = lsb + 2;
  2001. }
  2002. return lsb;
  2003. }
  2004. // Miscellaneous Bit Operations
  2005. int bitLength() {
  2006. if (n == -1) { // bitLength not initialized yet
  2007. int[] m = mag;
  2008. int len = m.size();
  2009. if (len == 0) {
  2010. n = 0; // offset by one to initialize
  2011. } else {
  2012. // Calculate the bit length of the magnitude
  2013. int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
  2014. if (signum < 0) {
  2015. // Check if magnitude is a power of two
  2016. bool pow2 = (__builtin_popcount(mag[0]) == 1);
  2017. for (int i=1; i< len && pow2; i++)
  2018. pow2 = (mag[i] == 0);
  2019. n = (pow2 ? magBitLength -1 : magBitLength);
  2020. } else {
  2021. n = magBitLength;
  2022. }
  2023. }
  2024. bitLength = n + 1;
  2025. }
  2026. return n;
  2027. }
  2028. int bitCount() {
  2029. if (bc == -1) { // bitCount not initialized yet
  2030. bc = 0; // offset by one to initialize
  2031. // Count the bits in the magnitude
  2032. for (int i=0; i < mag.size(); i++)
  2033. bc += __builtin_popcount(mag[i]);
  2034. if (signum < 0) {
  2035. // Count the trailing zeros in the magnitude
  2036. int magTrailingZeroCount = 0, j;
  2037. for (j=mag.length-1; mag[j] == 0; j--)
  2038. magTrailingZeroCount += 32;
  2039. magTrailingZeroCount += __builtin_ctz(mag[j]);
  2040. bc += magTrailingZeroCount - 1;
  2041. }
  2042. bitCount = bc + 1;
  2043. }
  2044. return bc;
  2045. }
  2046. // Primality Testing
  2047. bool isProbablePrime(int certainty) {
  2048. if (certainty <= 0)
  2049. return true;
  2050. BigInteger w = this->abs();
  2051. if (w.equals(TWO))
  2052. return true;
  2053. if (!w.testBit(0) || w.equals(ONE))
  2054. return false;
  2055. return w.primeToCertainty(certainty, null);
  2056. }
  2057. // Comparison Operations
  2058. int compareTo(BigInteger val) {
  2059. if (signum == val.signum) {
  2060. switch (signum) {
  2061. case 1:
  2062. return compareMagnitude(val);
  2063. case -1:
  2064. return val.compareMagnitude(this);
  2065. default:
  2066. return 0;
  2067. }
  2068. }
  2069. return signum > val.signum ? 1 : -1;
  2070. }
  2071. const int compareMagnitude(BigInteger val) {
  2072. std::vector<int> m1 = mag;
  2073. int len1 = m1.length;
  2074. std::vector<int> m2 = val.mag;
  2075. int len2 = m2.length;
  2076. if (len1 < len2)
  2077. return -1;
  2078. if (len1 > len2)
  2079. return 1;
  2080. for (int i = 0; i < len1; i++) {
  2081. int a = m1[i];
  2082. int b = m2[i];
  2083. if (a != b)
  2084. return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
  2085. }
  2086. return 0;
  2087. }
  2088. const int compareMagnitude(std::uint64_t val) {
  2089. std::vector<int> m1 = mag;
  2090. int len = m1.length;
  2091. if (len > 2) {
  2092. return 1;
  2093. }
  2094. if (val < 0) {
  2095. val = -val;
  2096. }
  2097. int highWord = (int)(val >> 32);
  2098. if (highWord == 0) {
  2099. if (len < 1)
  2100. return -1;
  2101. if (len > 1)
  2102. return 1;
  2103. int a = m1[0];
  2104. int b = (int)val;
  2105. if (a != b) {
  2106. return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
  2107. }
  2108. return 0;
  2109. } else {
  2110. if (len < 2)
  2111. return -1;
  2112. int a = m1[0];
  2113. int b = highWord;
  2114. if (a != b) {
  2115. return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
  2116. }
  2117. a = m1[1];
  2118. b = (int)val;
  2119. if (a != b) {
  2120. return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
  2121. }
  2122. return 0;
  2123. }
  2124. }
  2125. /*bool operator==(Object x) {
  2126. // This test is just an optimization, which may or may not help
  2127. if (x == this)
  2128. return true;
  2129. if (!(x instanceof BigInteger))
  2130. return false;
  2131. BigInteger xInt = (BigInteger) x;
  2132. if (xInt.signum != signum)
  2133. return false;
  2134. int[] m = mag;
  2135. int len = m.length;
  2136. int[] xm = xInt.mag;
  2137. if (len != xm.length)
  2138. return false;
  2139. for (int i = 0; i < len; i++)
  2140. if (xm[i] != m[i])
  2141. return false;
  2142. return true;
  2143. }*/
  2144. BigInteger min(BigInteger val) {
  2145. return (compareTo(val) < 0 ? *this : val);
  2146. }
  2147. BigInteger max(BigInteger val) {
  2148. return (compareTo(val) > 0 ? *this : val);
  2149. }
  2150. // Hash Function
  2151. int hashCode() {
  2152. int hashCode = 0;
  2153. for (int i=0; i < mag.size(); i++)
  2154. hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
  2155. return hashCode * signum;
  2156. }
  2157. /*std::string toString(int radix) {
  2158. if (signum == 0)
  2159. return "0";
  2160. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
  2161. radix = 10;
  2162. // If it's small enough, use smallToString.
  2163. if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD)
  2164. return smallToString(radix);
  2165. // Otherwise use recursive toString, which requires positive arguments.
  2166. // The results will be concatenated into this StringBuilder
  2167. StringBuilder sb = new StringBuilder();
  2168. if (signum < 0) {
  2169. toString(this.negate(), sb, radix, 0);
  2170. sb.insert(0, '-');
  2171. }
  2172. else
  2173. toString(this, sb, radix, 0);
  2174. return sb.toString();
  2175. }*/
  2176. /*String smallToString(int radix) {
  2177. if (signum == 0) {
  2178. return "0";
  2179. }
  2180. // Compute upper bound on number of digit groups and allocate space
  2181. int maxNumDigitGroups = (4*mag.length + 6)/7;
  2182. String digitGroup[] = new String[maxNumDigitGroups];
  2183. // Translate number to string, a digit group at a time
  2184. BigInteger tmp = this.abs();
  2185. int numGroups = 0;
  2186. while (tmp.signum != 0) {
  2187. BigInteger d = longRadix[radix];
  2188. MutableBigInteger q = MutableBigInteger(),
  2189. a = MutableBigInteger(tmp.mag),
  2190. b = MutableBigInteger(d.mag);
  2191. MutableBigInteger r = a.divide(b, q);
  2192. BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
  2193. BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
  2194. digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
  2195. tmp = q2;
  2196. }
  2197. // Put sign (if any) and first digit group into result buffer
  2198. StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
  2199. if (signum < 0) {
  2200. buf.append('-');
  2201. }
  2202. buf.append(digitGroup[numGroups-1]);
  2203. // Append remaining digit groups padded with leading zeros
  2204. for (int i=numGroups-2; i >= 0; i--) {
  2205. // Prepend (any) leading zeros for this digit group
  2206. int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
  2207. if (numLeadingZeros != 0) {
  2208. buf.append(zeros[numLeadingZeros]);
  2209. }
  2210. buf.append(digitGroup[i]);
  2211. }
  2212. return buf.toString();
  2213. }*/
  2214. /*static void toString(BigInteger u, StringBuilder sb, int radix, int digits) {
  2215. if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
  2216. String s = u.smallToString(radix);
  2217. // Pad with internal zeros if necessary.
  2218. // Don't pad if we're at the beginning of the string.
  2219. if ((s.length() < digits) && (sb.length() > 0)) {
  2220. for (int i=s.length(); i < digits; i++) { // May be a faster way to
  2221. sb.append('0'); // do this?
  2222. }
  2223. }
  2224. sb.append(s);
  2225. return;
  2226. }
  2227. int b, n;
  2228. b = u.bitLength();
  2229. // Calculate a value for n in the equation radix^(2^n) = u
  2230. // and subtract 1 from that value. This is used to find the
  2231. // cache index that contains the best value to divide u.
  2232. n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);
  2233. BigInteger v = getRadixConversionCache(radix, n);
  2234. BigInteger[] results;
  2235. results = u.divideAndRemainder(v);
  2236. int expectedDigits = 1 << n;
  2237. // Now recursively build the two halves of each number.
  2238. toString(results[0], sb, radix, digits-expectedDigits);
  2239. toString(results[1], sb, radix, expectedDigits);
  2240. }*/
  2241. /*static BigInteger getRadixConversionCache(int radix, int exponent) {
  2242. BigInteger[] cacheLine = powerCache[radix]; // volatile read
  2243. if (exponent < cacheLine.length) {
  2244. return cacheLine[exponent];
  2245. }
  2246. int oldLength = cacheLine.length;
  2247. cacheLine = Arrays.copyOf(cacheLine, exponent + 1);
  2248. for (int i = oldLength; i <= exponent; i++) {
  2249. cacheLine[i] = cacheLine[i - 1].pow(2);
  2250. }
  2251. BigInteger[][] pc = powerCache; // volatile read again
  2252. if (exponent >= pc[radix].length) {
  2253. pc = pc.clone();
  2254. pc[radix] = cacheLine;
  2255. powerCache = pc; // volatile write, publish
  2256. }
  2257. return cacheLine[exponent];
  2258. }*/
  2259. /* zero[i] is a string of i consecutive zeros. */
  2260. static std::string* zeros = new String[64];
  2261. static {
  2262. zeros[63] =
  2263. "000000000000000000000000000000000000000000000000000000000000000";
  2264. for (int i=0; i < 63; i++)
  2265. zeros[i] = std::string(zeros[63].begin(),zeros[63].begin() + i));
  2266. }
  2267. String toString() {
  2268. return toString(10);
  2269. }
  2270. std::vector<char> toByteArray() {
  2271. int byteLen = bitLength()/8 + 1;
  2272. std::vector<char> byteArray(byteLen);
  2273. for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
  2274. if (bytesCopied == 4) {
  2275. nextInt = getInt(intIndex++);
  2276. bytesCopied = 1;
  2277. } else {
  2278. nextInt >> 8;
  2279. bytesCopied++;
  2280. }
  2281. byteArray[i] = (byte)nextInt;
  2282. }
  2283. return byteArray;
  2284. }
  2285. int intValue() {
  2286. int result = 0;
  2287. result = getInt(0);
  2288. return result;
  2289. }
  2290. std::int64_t longValue() {
  2291. std::int64_t result = 0;
  2292. for (int i=1; i >= 0; i--)
  2293. result = (result << 32) + (getInt(i) & LONG_MASK);
  2294. return result;
  2295. }
  2296. /*float floatValue() {
  2297. if (signum == 0) {
  2298. return 0.0f;
  2299. }
  2300. int exponent = ((mag.size() - 1) << 5) + bitLengthForInt(mag[0]) - 1;
  2301. // exponent == floor(log2(abs(this)))
  2302. if (exponent < 64 - 1) {
  2303. return longValue();
  2304. } else if (exponent > 127) {
  2305. return signum > 0 ? (1.0f / 0.0f) : (-1.0f / 0.0f);
  2306. }
  2307. int shift = exponent - 24;
  2308. int twiceSignifFloor;
  2309. // twiceSignifFloor will be == abs().shiftRight(shift).intValue()
  2310. // We do the shift into an int directly to improve performance.
  2311. int nBits = shift & 0x1f;
  2312. int nBits2 = 32 - nBits;
  2313. if (nBits == 0) {
  2314. twiceSignifFloor = mag[0];
  2315. } else {
  2316. twiceSignifFloor = ((unsigned)mag[0]) >> nBits;
  2317. if (twiceSignifFloor == 0) {
  2318. twiceSignifFloor = (mag[0] << nBits2) | (((unsigned)mag[1]) >> nBits);
  2319. }
  2320. }
  2321. int signifFloor = twiceSignifFloor >> 1;
  2322. signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit
  2323. boolean increment = (twiceSignifFloor & 1) != 0
  2324. && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
  2325. int signifRounded = increment ? signifFloor + 1 : signifFloor;
  2326. int bits = ((exponent + FloatConsts.EXP_BIAS))
  2327. << (FloatConsts.SIGNIFICAND_WIDTH - 1);
  2328. bits += signifRounded;
  2329. bits |= signum & FloatConsts.SIGN_BIT_MASK;
  2330. return Float.intBitsToFloat(bits);
  2331. }*/
  2332. /*double doubleValue() {
  2333. if (signum == 0) {
  2334. return 0.0;
  2335. }
  2336. int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
  2337. // exponent == floor(log2(abs(this))Double)
  2338. if (exponent < Long.SIZE - 1) {
  2339. return longValue();
  2340. } else if (exponent > Double.MAX_EXPONENT) {
  2341. return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
  2342. }
  2343. int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;
  2344. long twiceSignifFloor;
  2345. // twiceSignifFloor will be == abs().shiftRight(shift).longValue()
  2346. // We do the shift into a long directly to improve performance.
  2347. int nBits = shift & 0x1f;
  2348. int nBits2 = 32 - nBits;
  2349. int highBits;
  2350. int lowBits;
  2351. if (nBits == 0) {
  2352. highBits = mag[0];
  2353. lowBits = mag[1];
  2354. } else {
  2355. highBits = mag[0] >>> nBits;
  2356. lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);
  2357. if (highBits == 0) {
  2358. highBits = lowBits;
  2359. lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);
  2360. }
  2361. }
  2362. twiceSignifFloor = ((highBits & LONG_MASK) << 32)
  2363. | (lowBits & LONG_MASK);
  2364. long signifFloor = twiceSignifFloor >> 1;
  2365. signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit
  2366. boolean increment = (twiceSignifFloor & 1) != 0
  2367. && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
  2368. long signifRounded = increment ? signifFloor + 1 : signifFloor;
  2369. long bits = (long) ((exponent + DoubleConsts.EXP_BIAS))
  2370. << (DoubleConsts.SIGNIFICAND_WIDTH - 1);
  2371. bits += signifRounded;
  2372. bits |= signum & DoubleConsts.SIGN_BIT_MASK;
  2373. return Double.longBitsToDouble(bits);
  2374. }*/
  2375. static std::vector<int> stripLeadingZeroInts(std::vector<int> val) {
  2376. int vlen = val.size();
  2377. int keep;
  2378. // Find first nonzero byte
  2379. for (keep = 0; keep < vlen && val[keep] == 0; keep++)
  2380. ;
  2381. return std::vector<int>(val.egin() + keep,val.begin() + keep + vlen);
  2382. }
  2383. static std::vector<int> trustedStripLeadingZeroInts(std::vector<int> val) {
  2384. int vlen = val.size();
  2385. int keep;
  2386. // Find first nonzero byte
  2387. for (keep = 0; keep < vlen && val[keep] == 0; keep++)
  2388. ;
  2389. return keep == 0 ? val : std::vector<int>(val.begin() + keep,val.begin() + keep + vlen);
  2390. }
  2391. static std::vector<int> stripLeadingZeroBytes(std::vector<char> a[]) {
  2392. unsigned int byteLength = a.size();
  2393. int keep;
  2394. // Find first nonzero byte
  2395. for (keep = 0; keep < byteLength && a[keep] == 0; keep++)
  2396. ;
  2397. // Allocate new array and copy relevant part of input array
  2398. int intLength = ((byteLength - keep) + 3u) >> 2;
  2399. std::vector<int> result(intLength);
  2400. int b = byteLength - 1;
  2401. for (int i = intLength-1; i >= 0; i--) {
  2402. result[i] = a[b--] & 0xff;
  2403. int bytesRemaining = b - keep + 1;
  2404. int bytesToTransfer = std::min(3, bytesRemaining);
  2405. for (int j=8; j <= (bytesToTransfer << 3); j += 8)
  2406. result[i] |= ((a[b--] & 0xff) << j);
  2407. }
  2408. return result;
  2409. }
  2410. static std::vector<int> makePositive(std::vector<char> a) {
  2411. int keep, k;
  2412. unsigned int byteLength = a.size();
  2413. // Find first non-sign (0xff) byte of input
  2414. for (keep=0; keep < byteLength && a[keep] == -1; keep++);
  2415. /* Allocate output array. If all non-sign bytes are 0x00, we must
  2416. * allocate space for one extra output byte. */
  2417. for (k=keep; k < byteLength && a[k] == 0; k++);
  2418. int extraByte = (k == byteLength) ? 1 : 0;
  2419. int intLength = ((byteLength - keep + extraByte) + 3u) >> 2;
  2420. std::vector<int> result(intLength);
  2421. /* Copy one's complement of input into output, leaving extra
  2422. * byte (if it exists) == 0x00 */
  2423. int b = byteLength - 1;
  2424. for (int i = intLength-1; i >= 0; i--) {
  2425. result[i] = a[b--] & 0xff;
  2426. int numBytesToTransfer = Math.min(3, b-keep+1);
  2427. if (numBytesToTransfer < 0)
  2428. numBytesToTransfer = 0;
  2429. for (int j=8; j <= 8*numBytesToTransfer; j += 8)
  2430. result[i] |= ((a[b--] & 0xff) << j);
  2431. // Mask indicates which bits must be complemented
  2432. int mask = -1 >>> (8*(3-numBytesToTransfer));
  2433. result[i] = ~result[i] & mask;
  2434. }
  2435. // Add one to one's complement to generate two's complement
  2436. for (int i=result.length-1; i >= 0; i--) {
  2437. result[i] = (int)((result[i] & LONG_MASK) + 1);
  2438. if (result[i] != 0)
  2439. break;
  2440. }
  2441. return result;
  2442. }
  2443. static std::vector<int> makePositive(std::vector<int> a) {
  2444. int keep, j;
  2445. // Find first non-sign (0xffffffff) int of input
  2446. for (keep=0; keep < a.size() && a[keep] == -1; keep++)
  2447. ;
  2448. /* Allocate output array. If all non-sign ints are 0x00, we must
  2449. * allocate space for one extra output int. */
  2450. for (j=keep; j < a.size() && a[j] == 0; j++)
  2451. ;
  2452. int extraInt = (j == a.length ? 1 : 0);
  2453. std::vector<int> result(a.length - keep + extraInt);
  2454. /* Copy one's complement of input into output, leaving extra
  2455. * int (if it exists) == 0x00 */
  2456. for (int i = keep; i < a.length; i++)
  2457. result[i - keep + extraInt] = ~a[i];
  2458. // Add one to one's complement to generate two's complement
  2459. for (int i = result.length-1; ++result[i] == 0; i--);
  2460. return result;
  2461. }
  2462. /*
  2463. * The following two arrays are used for fast String conversions. Both
  2464. * are indexed by radix. The first is the number of digits of the given
  2465. * radix that can fit in a Java long without "going negative", i.e., the
  2466. * highest integer n such that radix**n < 2**63. The second is the
  2467. * "long radix" that tears each number into "long digits", each of which
  2468. * consists of the number of digits in the corresponding element in
  2469. * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have
  2470. * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
  2471. * used.
  2472. */
  2473. static int digitsPerLong[] = {0, 0,
  2474. 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
  2475. 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
  2476. static BigInteger longRadix[] = {valueOf(0x4000000000000000L), valueOf(0x4000000000000000L),
  2477. valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
  2478. valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
  2479. valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
  2480. valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
  2481. valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
  2482. valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
  2483. valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
  2484. valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
  2485. valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
  2486. valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
  2487. valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
  2488. valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
  2489. valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
  2490. valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
  2491. valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
  2492. valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
  2493. valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
  2494. valueOf(0x41c21cb8e1000000L)};
  2495. /*
  2496. * These two arrays are the integer analogue of above.
  2497. */
  2498. static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
  2499. 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  2500. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
  2501. static int intRadix[] = {0, 0,
  2502. 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
  2503. 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
  2504. 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,
  2505. 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
  2506. 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,
  2507. 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
  2508. 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
  2509. };
  2510. int intLength() {
  2511. return ((unsigned)bitLength() >> 5) + 1;
  2512. }
  2513. /* Returns sign bit */
  2514. int signBit() {
  2515. return signum < 0 ? 1 : 0;
  2516. }
  2517. /* Returns an int of sign bits */
  2518. int signInt() {
  2519. return signum < 0 ? -1 : 0;
  2520. }
  2521. int getInt(int n) {
  2522. if (n < 0)
  2523. return 0;
  2524. if (n >= mag.length)
  2525. return signInt();
  2526. int magInt = mag[mag.length - n - 1];
  2527. return (signum >= 0 ? magInt :
  2528. (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
  2529. }
  2530. int firstNonzeroIntNum() {
  2531. int fn = firstNonzeroIntNum - 2;
  2532. if (fn == -2) { // firstNonzeroIntNum not initialized yet
  2533. fn = 0;
  2534. // Search for the first nonzero int
  2535. int i;
  2536. int mlen = mag.length;
  2537. for (i = mlen - 1; i >= 0 && mag[i] == 0; i--);
  2538. fn = mlen - i - 1;
  2539. firstNonzeroIntNum = fn + 2; // offset by two to initialize
  2540. }
  2541. return fn;
  2542. }
  2543. static const long serialVersionUID = -8287574255936472291L;
  2544. std::vector<char> magSerializedForm() {
  2545. int len = mag.length;
  2546. int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
  2547. int byteLen = (bitLen + 7) >>> 3;
  2548. byte[] result = new byte[byteLen];
  2549. for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
  2550. i >= 0; i--) {
  2551. if (bytesCopied == 4) {
  2552. nextInt = mag[intIndex--];
  2553. bytesCopied = 1;
  2554. } else {
  2555. nextInt >>>= 8;
  2556. bytesCopied++;
  2557. }
  2558. result[i] = (byte)nextInt;
  2559. }
  2560. return result;
  2561. }
  2562. std::int64_t longValueExact() {
  2563. if (mag.length <= 2 && bitLength() <= 63)
  2564. return longValue();
  2565. else
  2566. throw std::logic_error("BigInteger out of long range");
  2567. }
  2568. int intValueExact() {
  2569. if (mag.length <= 1 && bitLength() <= 31)
  2570. return intValue();
  2571. else
  2572. throw std::logic_error("BigInteger out of int range");
  2573. }
  2574. short shortValueExact() {
  2575. if (mag.length <= 1 && bitLength() <= 31) {
  2576. int value = intValue();
  2577. if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)
  2578. return shortValue();
  2579. }
  2580. throw std::logic_error("BigInteger out of short range");
  2581. }
  2582. char byteValueExact() {
  2583. if (mag.length <= 1 && bitLength() <= 31) {
  2584. int value = intValue();
  2585. if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)
  2586. return byteValue();
  2587. }
  2588. throw std::logic_error("BigInteger out of byte range");
  2589. }
  2590. };
  2591. int main() {
  2592. BigInteger a(6);
  2593. a = a.pow(100);
  2594. }