BigInteger.cpp 104 KB

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