123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372 |
- #include <vector>
- #include <algorithm>
- #include <cstring>
- #include <iterator>
- #include <stdexcept>
- #include <cstdint>
- #include <cassert>
- using std::uint64_t;
- class BigInteger{
- const int signum;
- std::vector<int> mag;
- int bitCount;
- int bitLength;
- int lowestSetBit;
- int firstNonzeroIntNum;
- const static uint64_t LONG_MASK = 0xffffffffL;
- static const int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26)
- static const int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000;
- static const int KARATSUBA_THRESHOLD = 80;
- static const int TOOM_COOK_THRESHOLD = 240;
- static const int KARATSUBA_SQUARE_THRESHOLD = 128;
- static const int TOOM_COOK_SQUARE_THRESHOLD = 216;
- static const int BURNIKEL_ZIEGLER_THRESHOLD = 80;
- static const int BURNIKEL_ZIEGLER_OFFSET = 40;
- static const int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20;
- static const int MULTIPLY_SQUARE_THRESHOLD = 20;
- static const int MONTGOMERY_INTRINSIC_THRESHOLD = 512;
- BigInteger(std::vector<char> val) {
- assert(val.size() != 0);
- if (val[0] < 0) {
- mag = makePositive(val);
- signum = -1;
- } else {
- mag = stripLeadingZeroBytes(val);
- signum = (mag.length == 0 ? 0 : 1);
- }
- if (mag.size() >= MAX_MAG_LENGTH) {
- checkRange();
- }
- }
-
- BigInteger(std::vector<int> val) {
- assert(val.size() != 0);
- if (val[0] < 0) {
- mag = makePositive(val);
- signum = -1;
- } else {
- mag = trustedStripLeadingZeroInts(val);
- signum = (mag.size() == 0 ? 0 : 1);
- }
- if (mag.size() >= MAX_MAG_LENGTH) {
- checkRange();
- }
- }
-
-
- BigInteger(int signum, std::vector<char> magnitude) {
- mag = stripLeadingZeroBytes(magnitude);
- assert(!(signum < -1 || signum > 1));
- if (mag.size() == 0) {
- signum = 0;
- } else {
- assert(signum != 0);
- signum = signum;
- }
- if (mag.size() >= MAX_MAG_LENGTH) {
- checkRange();
- }
- }
-
- BigInteger(int signum, std::vector<int> magnitude) {
- mag = stripLeadingZeroInts(magnitude);
- assert(!(signum < -1 || signum > 1));
- if (this.mag.length == 0) {
- signum = 0;
- } else {
- assert(signum != 0);
- signum = signum;
- }
- if (mag.length >= MAX_MAG_LENGTH) {
- checkRange();
- }
- }
-
- /*
- * Constructs a new BigInteger using a char array with radix=10.
- * Sign is precalculated outside and not allowed in the val.
- */
- BigInteger(std::vector<char> val, int sign, int len) {
- int cursor = 0, numDigits;
- // Skip leading zeros and compute number of digits in magnitude
- while (cursor < len && Character.digit(val[cursor], 10) == 0) {
- cursor++;
- }
- if (cursor == len) {
- signum = 0;
- mag = ZERO.mag;
- return;
- }
- numDigits = len - cursor;
- signum = sign;
- // Pre-allocate array of expected size
- unsigned int numWords;
- if (len < 10) {
- numWords = 1;
- } else {
- uint64_t numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1;
- if (numBits + 31 >= (1L << 32)) {
- reportOverflow();
- }
- numWords = (int) (numBits + 31) >>> 5;
- }
- std::vector<int> magnitude(numBits);
- // Process first (potentially short) digit group
- int firstGroupLen = numDigits % digitsPerInt[10];
- if (firstGroupLen == 0)
- firstGroupLen = digitsPerInt[10];
- magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen);
- // Process remaining digit groups
- while (cursor < len) {
- int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]);
- destructiveMulAdd(magnitude, intRadix[10], groupVal);
- }
- mag = trustedStripLeadingZeroInts(magnitude);
- if (mag.length >= MAX_MAG_LENGTH) {
- checkRange();
- }
- }
- int digit(char a){
- assert((int)(a - '0') < 10 && (int)(a - '0') >= 0);
- return (int)(a - '0');
- }
- // Create an integer with the digits between the two indexes
- // Assumes start < end. The result may be negative, but it
- // is to be treated as an unsigned value.
- int parseInt(const std::vector<char>& source, int start, int end) {
- int result = digit(source[start++]);
-
- for (int index = start; index < end; index++) {
- int nextVal = digit(source[index]);
- result = 10 * result + nextVal;
- }
- return result;
- }
- // bitsPerDigit in the given radix times 1024
- // Rounded up to avoid underallocation.
- static uint64_t bitsPerDigit[] = { 0, 0,
- 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672,
- 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633,
- 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210,
- 5253, 5295};
- // Multiply x array times word y in place, and add word z
- static void destructiveMulAdd(std::vector<int>& x, int y, int z) {
- // Perform the multiplication word by word
- uint64_t ylong = y & LONG_MASK;
- uint64_t zlong = z & LONG_MASK;
- int len = x.length;
- uint64_t product = 0;
- uint64_t carry = 0;
- for (int i = len-1; i >= 0; i--) {
- product = ylong * (x[i] & LONG_MASK) + carry;
- x[i] = (int)product;
- carry = product >>> 32;
- }
- // Perform the addition
- uint64_t sum = (x[len-1] & LONG_MASK) + zlong;
- x[len-1] = (int)sum;
- carry = sum >> 32;
- for (int i = len-2; i >= 0; i--) {
- sum = (x[i] & LONG_MASK) + carry;
- x[i] = (int)sum;
- carry = sum >> 32;
- }
- }
-
- BigInteger(std::string val) : BigInteger(val, 10) {
-
- }
-
- BigInteger(int numBits, std::mt19937_64& rnd) : BigInteger(1, randomBits(numBits, rnd)) {
-
- }
- static std::vector<char> randomBits(unsigned int numBits, std::mt19937_64& rnd) {
- unsigned int numBytes = (unsigned int)(((uint64_t)numBits+7)/8); // avoid overflow
- std::vector<char> randomBits(numBytes);
- std::uniform_int_distribution<char> dis(-128,127);
- // Generate random bytes and mask out any excess bits
- if (numBytes > 0) {
- std::generate(randomBits.begin(), randomBits.end(), [&](){return dis(rnd)});
- int excessBits = 8*numBytes - numBits;
- randomBits[0] &= (1 << (8-excessBits)) - 1;
- }
- return randomBits;
- }
-
- BigInteger(int bitLength, int certainty, std::mt19937_64& rnd) {
- BigInteger prime;
- assert(bitLength >= 2);
- prime = (bitLength < SMALL_PRIME_THRESHOLD
- ? smallPrime(bitLength, certainty, rnd)
- : largePrime(bitLength, certainty, rnd));
- signum = 1;
- mag = prime.mag;
- }
- // Minimum size in bits that the requested prime number has
- // before we use the large prime number generating algorithms.
- // The cutoff of 95 was chosen empirically for best performance.
- static const int SMALL_PRIME_THRESHOLD = 95;
- // Certainty required to meet the spec of probablePrime
- static const int DEFAULT_PRIME_CERTAINTY = 100;
-
- /*static BigInteger probablePrime(int bitLength, Random rnd) {
- if (bitLength < 2)
- throw new ArithmeticException("bitLength < 2");
- return (bitLength < SMALL_PRIME_THRESHOLD ?
- smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) :
- largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd));
- }
-
- static BigInteger smallPrime(int bitLength, int certainty, Random rnd) {
- int magLen = (bitLength + 31) >>> 5;
- int temp[] = new int[magLen];
- int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int
- int highMask = (highBit << 1) - 1; // Bits to keep in high int
- while (true) {
- // Construct a candidate
- for (int i=0; i < magLen; i++)
- temp[i] = rnd.nextInt();
- temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length
- if (bitLength > 2)
- temp[magLen-1] |= 1; // Make odd if bitlen > 2
- BigInteger p = new BigInteger(temp, 1);
- // Do cheap "pre-test" if applicable
- if (bitLength > 6) {
- long r = p.remainder(SMALL_PRIME_PRODUCT).longValue();
- if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
- (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
- (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0))
- continue; // Candidate is composite; try another
- }
- // All candidates of bitLength 2 and 3 are prime by this point
- if (bitLength < 4)
- return p;
- // Do expensive test if we survive pre-test (or it's inapplicable)
- if (p.primeToCertainty(certainty, rnd))
- return p;
- }
- }
- static const BigInteger SMALL_PRIME_PRODUCT
- = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41);
-
- static BigInteger largePrime(int bitLength, int certainty, Random rnd) {
- BigInteger p;
- p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
- p.mag[p.mag.length-1] &= 0xfffffffe;
- // Use a sieve length likely to contain the next prime number
- int searchLen = getPrimeSearchLen(bitLength);
- BitSieve searchSieve = new BitSieve(p, searchLen);
- BigInteger candidate = searchSieve.retrieve(p, certainty, rnd);
- while ((candidate == null) || (candidate.bitLength() != bitLength)) {
- p = p.add(BigInteger.valueOf(2*searchLen));
- if (p.bitLength() != bitLength)
- p = new BigInteger(bitLength, rnd).setBit(bitLength-1);
- p.mag[p.mag.length-1] &= 0xfffffffe;
- searchSieve = new BitSieve(p, searchLen);
- candidate = searchSieve.retrieve(p, certainty, rnd);
- }
- return candidate;
- }
-
- BigInteger nextProbablePrime() {
- if (this.signum < 0)
- throw new ArithmeticException("start < 0: " + this);
- // Handle trivial cases
- if ((this.signum == 0) || this.equals(ONE))
- return TWO;
- BigInteger result = this.add(ONE);
- // Fastpath for small numbers
- if (result.bitLength() < SMALL_PRIME_THRESHOLD) {
- // Ensure an odd number
- if (!result.testBit(0))
- result = result.add(ONE);
- while (true) {
- // Do cheap "pre-test" if applicable
- if (result.bitLength() > 6) {
- long r = result.remainder(SMALL_PRIME_PRODUCT).longValue();
- if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) ||
- (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) ||
- (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) {
- result = result.add(TWO);
- continue; // Candidate is composite; try another
- }
- }
- // All candidates of bitLength 2 and 3 are prime by this point
- if (result.bitLength() < 4)
- return result;
- // The expensive test
- if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null))
- return result;
- result = result.add(TWO);
- }
- }
- // Start at previous even number
- if (result.testBit(0))
- result = result.subtract(ONE);
- // Looking for the next large prime
- int searchLen = getPrimeSearchLen(result.bitLength());
- while (true) {
- BitSieve searchSieve = new BitSieve(result, searchLen);
- BigInteger candidate = searchSieve.retrieve(result,
- DEFAULT_PRIME_CERTAINTY, null);
- if (candidate != null)
- return candidate;
- result = result.add(BigInteger.valueOf(2 * searchLen));
- }
- }
- static int getPrimeSearchLen(int bitLength) {
- if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) {
- throw new ArithmeticException("Prime search implementation restriction on bitLength");
- }
- return bitLength / 20 * 64;
- }*/
-
- bool primeToCertainty(int certainty, std::mt19937_64& random) {
- int rounds = 0;
- int n = (std::min(certainty, Integer.MAX_VALUE-1)+1)/2;
- // The relationship between the certainty and the number of rounds
- // we perform is given in the draft standard ANSI X9.80, "PRIME
- // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES".
- int sizeInBits = bitLength();
- if (sizeInBits < 100) {
- rounds = 50;
- rounds = n < rounds ? n : rounds;
- return passesMillerRabin(rounds, random);
- }
- if (sizeInBits < 256) {
- rounds = 27;
- } else if (sizeInBits < 512) {
- rounds = 15;
- } else if (sizeInBits < 768) {
- rounds = 8;
- } else if (sizeInBits < 1024) {
- rounds = 4;
- } else {
- rounds = 2;
- }
- rounds = n < rounds ? n : rounds;
- return passesMillerRabin(rounds, random) && passesLucasLehmer();
- }
-
- boolean passesLucasLehmer() {
- BigInteger thisPlusOne = this->add(ONE);
- // Step 1
- int d = 5;
- while (jacobiSymbol(d, this) != -1) {
- // 5, -7, 9, -11, ...
- d = (d < 0) ? std::abs(d)+2 : -(d+2);
- }
- // Step 2
- BigInteger u = lucasLehmerSequence(d, thisPlusOne, *this);
- // Step 3
- return u.mod(*this).equals(ZERO);
- }
-
- static int jacobiSymbol(int p, BigInteger n) {
- if (p == 0)
- return 0;
- // Algorithm and comments adapted from Colin Plumb's C library.
- int j = 1;
- int u = n.mag[n.mag.length-1];
- // Make p positive
- if (p < 0) {
- p = -p;
- int n8 = u & 7;
- if ((n8 == 3) || (n8 == 7))
- j = -j; // 3 (011) or 7 (111) mod 8
- }
- // Get rid of factors of 2 in p
- while ((p & 3) == 0)
- p >>= 2;
- if ((p & 1) == 0) {
- p >>= 1;
- if (((u ^ (u>>1)) & 2) != 0)
- j = -j; // 3 (011) or 5 (101) mod 8
- }
- if (p == 1)
- return j;
- // Then, apply quadratic reciprocity
- if ((p & u & 2) != 0) // p = u = 3 (mod 4)?
- j = -j;
- // And reduce u mod p
- u = n.mod(BigInteger::valueOf(p)).intValue();
- // Now compute Jacobi(u,p), u < p
- while (u != 0) {
- while ((u & 3) == 0)
- u >>= 2;
- if ((u & 1) == 0) {
- u >>= 1;
- if (((p ^ (p>>1)) & 2) != 0)
- j = -j; // 3 (011) or 5 (101) mod 8
- }
- if (u == 1)
- return j;
- // Now both u and p are odd, so use quadratic reciprocity
- assert (u < p);
- int t = u; u = p; p = t;
- if ((u & p & 2) != 0) // u = p = 3 (mod 4)?
- j = -j;
- // Now u >= p, so it can be reduced
- u %= p;
- }
- return 0;
- }
- static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) {
- BigInteger d = BigInteger::valueOf(z);
- BigInteger u = ONE; BigInteger u2;
- BigInteger v = ONE; BigInteger v2;
- for (int i=k.bitLength()-2; i >= 0; i--) {
- u2 = u.multiply(v).mod(n);
- v2 = v.square().add(d.multiply(u.square())).mod(n);
- if (v2.testBit(0))
- v2 = v2.subtract(n);
- v2 = v2.shiftRight(1);
- u = u2; v = v2;
- if (k.testBit(i)) {
- u2 = u.add(v).mod(n);
- if (u2.testBit(0))
- u2 = u2.subtract(n);
- u2 = u2.shiftRight(1);
- v2 = v.add(d.multiply(u)).mod(n);
- if (v2.testBit(0))
- v2 = v2.subtract(n);
- v2 = v2.shiftRight(1);
- u = u2; v = v2;
- }
- }
- return u;
- }
-
- bool passesMillerRabin(int iterations, std::mt19937_64& rnd) {
- // Find a and m such that m is odd and this == 1 + 2**a * m
- BigInteger thisMinusOne = this->subtract(ONE);
- BigInteger m = thisMinusOne;
- int a = m.getLowestSetBit();
- m = m.shiftRight(a);
- // Do the tests
- for (int i=0; i < iterations; i++) {
- // Generate a uniform random on (1, this)
- BigInteger b;
- do {
- b = BigInteger(this->bitLength(), rnd);
- } while (b.compareTo(ONE) <= 0 || b.compareTo(*this) >= 0);
- int j = 0;
- BigInteger z = b.modPow(m, *this);
- while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) {
- if (j > 0 && z.equals(ONE) || ++j == a)
- return false;
- z = z.modPow(TWO, *this);
- }
- }
- return true;
- }
-
- BigInteger(const std::vector<int> magnitude&, int signum) {
- this.signum = (magnitude.siz() == 0 ? 0 : signum);
- this.mag = magnitude;
- if (mag.length >= MAX_MAG_LENGTH) {
- checkRange();
- }
- }
-
- BigInteger(const std::vector<int> magnitude&e, int signum) {
- signum = (magnitude.length == 0 ? 0 : signum);
- mag = stripLeadingZeroBytes(magnitude);
- if (mag.length >= MAX_MAG_LENGTH) {
- checkRange();
- }
- }
-
- void checkRange() {
- if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) {
- reportOverflow();
- }
- }
- static void reportOverflow() {
- std::cout << "BigInteger would overflow supported range" << std::endl;
- throw 1;
- }
- //Static Factory Methods
-
- static BigInteger valueOf(std::int64_t val) {
- // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
- if (val == 0)
- return ZERO;
- if (val > 0 && val <= MAX_CONSTANT)
- return posConst[(int) val];
- else if (val < 0 && val >= -MAX_CONSTANT)
- return negConst[(int) -val];
- return BigInteger(val);
- }
-
- BigInteger(std::int64_t val) {
- if (val < 0) {
- val = -val;
- signum = -1;
- } else {
- signum = 1;
- }
- int highWord = (int)(((uint64_t)val) >> 32);
- if (highWord == 0) {
- mag = std::vector<int>(1);
- mag[0] = (int)val;
- } else {
- mag = std::vector<int>(2);
- mag[0] = highWord;
- mag[1] = (int)val;
- }
- }
-
- static BigInteger valueOf(std::vector<int> val) {
- return (val[0] > 0 ? BigInteger(val, 1) : BigInteger(val));
- }
- // Constants
-
- const static int MAX_CONSTANT = 16;
- static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
- static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
-
- static volatile BigInteger[][] powerCache;
-
- static const double[] logCache;
-
- static const double LOG_TWO = Math.log(2.0);
- static void initStuff(){
- for (int i = 1; i <= MAX_CONSTANT; i++) {
- std::vector<int> magnitude(1);
- magnitude[0] = i;
- posConst[i] = BigInteger(magnitude, 1);
- negConst[i] = BigInteger(magnitude, -1);
- }
- /*
- * Initialize the cache of radix^(2^x) values used for base conversion
- * with just the very first value. Additional values will be created
- * on demand.
- */
- powerCache = new BigInteger[Character.MAX_RADIX+1][];
- logCache = new double[Character.MAX_RADIX+1];
- for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) {
- powerCache[i] = new BigInteger[] { BigInteger.valueOf(i) };
- logCache[i] = Math.log(i);
- }
- }
-
- static const BigInteger ZERO = new BigInteger(std::vector<int>(0), 0);
-
- static const BigInteger ONE = valueOf(1);
-
- static const BigInteger TWO = valueOf(2);
-
- static const BigInteger NEGATIVE_ONE = valueOf(-1);
-
- static const BigInteger TEN = valueOf(10);
- // Arithmetic Operations
-
- BigInteger add(BigInteger val) {
- if (val.signum == 0)
- return *this;
- if (signum == 0)
- return val;
- if (val.signum == signum)
- return BigInteger(add(mag, val.mag), signum);
- int cmp = compareMagnitude(val);
- if (cmp == 0)
- return ZERO;
- std::vector<int> resultMag = (cmp > 0 ? subtract(mag, val.mag)
- : subtract(val.mag, mag));
- resultMag = trustedStripLeadingZeroInts(resultMag);
- return BigInteger(resultMag, cmp == signum ? 1 : -1);
- }
- static int signum(std::int64_t a){
- if(a == 0)return 0;
- if(a > 0)return 1;
- return -1;
- }
-
- BigInteger add(std::int64_t val) {
- if (val == 0)
- return *this;
- if (signum == 0)
- return valueOf(val);
- if (signum(val) == signum)
- return BigInteger(add(mag, Math.abs(val)), signum);
- int cmp = compareMagnitude(val);
- if (cmp == 0)
- return ZERO;
- std::vector<int> resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag));
- resultMag = trustedStripLeadingZeroInts(resultMag);
- return BigInteger(resultMag, cmp == signum ? 1 : -1);
- }
-
- static std::vector<int> add(std::vector<int> x, std::uint64_t val) {
- std::vector<int> y;
- long sum = 0;
- int xIndex = x.size();
- std::vector<int> result;
- int highWord = (int)(val >>> 32);
- if (highWord == 0) {
- result = std::vector<int>(xIndex);
- sum = (x[--xIndex] & LONG_MASK) + val;
- result[xIndex] = (int)sum;
- } else {
- if (xIndex == 1) {
- result = std::vector<int>(2);
- sum = val + (x[0] & LONG_MASK);
- result[1] = (int)sum;
- result[0] = (int)(sum >>> 32);
- return result;
- } else {
- result = std::vector<int>(xIndex);
- sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK);
- result[xIndex] = (int)sum;
- sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32);
- result[xIndex] = (int)sum;
- }
- }
- // Copy remainder of longer number while carry propagation is required
- bool carry = (sum >>> 32 != 0);
- while (xIndex > 0 && carry)
- carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
- // Copy remainder of longer number
- while (xIndex > 0)
- result[--xIndex] = x[xIndex];
- // Grow result if necessary
- if (carry) {
- std::vector<int> bigger(result.length + 1);
- //System.arraycopy(result, 0, bigger, 1, result.length);
- std::copy(result.begin(),result.end(), bigger.begin());
- bigger[0] = 0x01;
- return bigger;
- }
- return result;
- }
-
- static std::vector<int> add(std::vector<int> x, std::vector<int> y) {
- // If x is shorter, swap the two arrays
- if (x.size() < y.size()) {
- std::swap(x,y);
- /*int[] tmp = x;
- x = y;
- y = tmp;*/
- }
- int xIndex = x.length;
- int yIndex = y.length;
- std::vector<int> result(xIndex);// = new int[xIndex];
- long sum = 0;
- if (yIndex == 1) {
- sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ;
- result[xIndex] = (int)sum;
- } else {
- // Add common parts of both numbers
- while (yIndex > 0) {
- sum = (x[--xIndex] & LONG_MASK) +
- (y[--yIndex] & LONG_MASK) + (sum >>> 32);
- result[xIndex] = (int)sum;
- }
- }
- // Copy remainder of longer number while carry propagation is required
- boolean carry = (sum >>> 32 != 0);
- while (xIndex > 0 && carry)
- carry = ((result[--xIndex] = x[xIndex] + 1) == 0);
- // Copy remainder of longer number
- while (xIndex > 0)
- result[--xIndex] = x[xIndex];
- // Grow result if necessary
- if (carry) {
- std::vector<int> bigger(result.length + 1);
- std::copy(result.begin(),result.end(),bigger.begin());
- bigger[0] = 0x01;
- return bigger;
- }
- return result;
- }
- static int[] subtract(std::int64_t val, int[] little) {
- int highWord = (int)(((uint64_t)val) >> 32);
- if (highWord == 0) {
- std::vector<int>result(1);
- result[0] = (int)(val - (little[0] & LONG_MASK));
- return result;
- } else {
- std::vector<int> result(2);
- if (little.length == 1) {
- std::int64_t difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK);
- result[1] = (int)difference;
- // Subtract remainder of longer number while borrow propagates
- bool borrow = (difference >> 32 != 0);
- if (borrow) {
- result[0] = highWord - 1;
- } else { // Copy remainder of longer number
- result[0] = highWord;
- }
- return result;
- } else { // little.length == 2
- std::int64_t difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK);
- result[1] = (int)difference;
- difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32);
- result[0] = (int)difference;
- return result;
- }
- }
- }
-
- static std::vector<int> subtract(std::vector<int> big, std::int64_t val) {
- int highWord = (int)(((uint64_t)val) >> 32);
- int bigIndex = big.size();
- std::vector<int> result(bigIndex);
- long difference = 0;
- if (highWord == 0) {
- difference = (big[--bigIndex] & LONG_MASK) - val;
- result[bigIndex] = (int)difference;
- } else {
- difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK);
- result[bigIndex] = (int)difference;
- difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32);
- result[bigIndex] = (int)difference;
- }
- // Subtract remainder of longer number while borrow propagates
- boolean borrow = (difference >> 32 != 0);
- while (bigIndex > 0 && borrow)
- borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
- // Copy remainder of longer number
- while (bigIndex > 0)
- result[--bigIndex] = big[bigIndex];
- return result;
- }
-
- BigInteger subtract(BigInteger val) {
- if (val.signum == 0)
- return *this;
- if (signum == 0)
- return val.negate();
- if (val.signum != signum)
- return BigInteger(add(mag, val.mag), signum);
- int cmp = compareMagnitude(val);
- if (cmp == 0)
- return ZERO;
- std::vector<int> resultMag = (cmp > 0 ? subtract(mag, val.mag)
- : subtract(val.mag, mag));
- resultMag = trustedStripLeadingZeroInts(resultMag);
- return BigInteger(resultMag, cmp == signum ? 1 : -1);
- }
-
- static std::vector<int> subtract(std::vector<int> big, std::vector<int> little) {
- int bigIndex = big.size();
- std::vector<int> result(bigIndex);
- int littleIndex = little.size();
- std::int64_t difference = 0;
- // Subtract common parts of both numbers
- while (littleIndex > 0) {
- difference = (big[--bigIndex] & LONG_MASK) -
- (little[--littleIndex] & LONG_MASK) +
- (difference >> 32);
- result[bigIndex] = (int)difference;
- }
- // Subtract remainder of longer number while borrow propagates
- bool borrow = (difference >> 32 != 0);
- while (bigIndex > 0 && borrow)
- borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1);
- // Copy remainder of longer number
- while (bigIndex > 0)
- result[--bigIndex] = big[bigIndex];
- return result;
- }
-
- BigInteger multiply(BigInteger val) {
- if (val.signum == 0 || signum == 0)
- return ZERO;
- int xlen = mag.size();
- if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) {
- return square();
- }
- int ylen = val.mag.size();
- if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) {
- int resultSign = signum == val.signum ? 1 : -1;
- if (val.mag.size() == 1) {
- return multiplyByInt(mag,val.mag[0], resultSign);
- }
- if (mag.size() == 1) {
- return multiplyByInt(val.mag,mag[0], resultSign);
- }
- std::vector<int> result = multiplyToLen(mag, xlen,
- val.mag, ylen, null);
- result = trustedStripLeadingZeroInts(result);
- return BigInteger(result, resultSign);
- } else {
- if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) {
- return multiplyKaratsuba(this, val);
- } else {
- return multiplyToomCook3(this, val);
- }
- }
- }
- static BigInteger multiplyByInt(std::vector<int> x, int y, int sign) {
- if (__builtin_popcount(y) == 1) {
- return BigInteger(shiftLeft(x,__builtin_ctz(y)), sign);
- }
- int xlen = x.length;
- std::vector<int> rmag(xlen + 1);
- long carry = 0;
- long yl = y & LONG_MASK;
- int rstart = rmag.length - 1;
- for (int i = xlen - 1; i >= 0; i--) {
- std::uint64_t product = (x[i] & LONG_MASK) * yl + carry;
- rmag[rstart--] = (int)product;
- carry = product >> 32;
- }
- if (carry == 0L) {
- rmag.erase(rmag.begin());
- } else {
- rmag[rstart] = (int)carry;
- }
- return BigInteger(rmag, sign);
- }
-
- BigInteger multiply(std::uint64_t v) {
- if (v == 0 || signum == 0)
- return ZERO;
- if (v == std::numeric_limits<std::uint64_t>::max())
- return multiply(BigInteger.valueOf(v));
- int rsign = (v > 0 ? signum : -signum);
- if (v < 0)
- v = -v;
- uint64_t dh = v >> 32; // higher order bits
- uint64_t dl = v & LONG_MASK; // lower order bits
- int xlen = mag.length;
- std::vector<int> value = mag;
- std::vector<int> rmag = (dh == 0L) ? (std::vector<int>([xlen + 1])) : (std::vector<int>([xlen + 2]));
- uint64_t carry = 0;
- int rstart = rmag.length - 1;
- for (int i = xlen - 1; i >= 0; i--) {
- uint64_t product = (value[i] & LONG_MASK) * dl + carry;
- rmag[rstart--] = (int)product;
- carry = product >> 32;
- }
- rmag[rstart] = (int)carry;
- if (dh != 0L) {
- carry = 0;
- rstart = rmag.length - 2;
- for (int i = xlen - 1; i >= 0; i--) {
- long product = (value[i] & LONG_MASK) * dh +
- (rmag[rstart] & LONG_MASK) + carry;
- rmag[rstart--] = (int)product;
- carry = product >> 32;
- }
- rmag[0] = (int)carry;
- }
- if (carry == 0LL)
- rmag.erase(rmag.begin());
- return BigInteger(rmag, rsign);
- }
-
- static std::vector<int> multiplyToLen(std::vector<int> x, int xlen, std::vector<int> y, int ylen, std::vector<int> z) {
- int xstart = xlen - 1;
- int ystart = ylen - 1;
- if (z.length < (xlen+ ylen))
- z = std::vector<int>(xlen+ylen);
- uint64_t carry = 0;
- for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) {
- long product = (y[j] & LONG_MASK) *
- (x[xstart] & LONG_MASK) + carry;
- z[k] = (int)product;
- carry = product >> 32;
- }
- z[xstart] = (int)carry;
- for (int i = xstart-1; i >= 0; i--) {
- carry = 0;
- for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) {
- long product = (y[j] & LONG_MASK) *
- (x[i] & LONG_MASK) +
- (z[k] & LONG_MASK) + carry;
- z[k] = (int)product;
- carry = product >> 32;
- }
- z[i] = (int)carry;
- }
- return z;
- }
-
- static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) {
- int xlen = x.mag.size();
- int ylen = y.mag.size();
- // The number of ints in each half of the number.
- int half = (std::max(xlen, ylen)+1) / 2;
- // xl and yl are the lower halves of x and y respectively,
- // xh and yh are the upper halves.
- BigInteger xl = x.getLower(half);
- BigInteger xh = x.getUpper(half);
- BigInteger yl = y.getLower(half);
- BigInteger yh = y.getUpper(half);
- BigInteger p1 = xh.multiply(yh); // p1 = xh*yh
- BigInteger p2 = xl.multiply(yl); // p2 = xl*yl
- // p3=(xh+xl)*(yh+yl)
- BigInteger p3 = xh.add(xl).multiply(yh.add(yl));
- // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2
- BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2);
- if (x.signum != y.signum) {
- return result.negate();
- } else {
- return result;
- }
- }
-
- static BigInteger multiplyToomCook3(BigInteger a, BigInteger b) {
- int alen = a.mag.size();
- int blen = b.mag.size();
- int largest = std::max(alen, blen);
- // k is the size (in ints) of the lower-order slices.
- int k = (largest+2)/3; // Equal to ceil(largest/3)
- // r is the size (in ints) of the highest-order slice.
- int r = largest - 2*k;
- // Obtain slices of the numbers. a2 and b2 are the most significant
- // bits of the numbers a and b, and a0 and b0 the least significant.
- BigInteger a0, a1, a2, b0, b1, b2;
- a2 = a.getToomSlice(k, r, 0, largest);
- a1 = a.getToomSlice(k, r, 1, largest);
- a0 = a.getToomSlice(k, r, 2, largest);
- b2 = b.getToomSlice(k, r, 0, largest);
- b1 = b.getToomSlice(k, r, 1, largest);
- b0 = b.getToomSlice(k, r, 2, largest);
- BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1;
- v0 = a0.multiply(b0);
- da1 = a2.add(a0);
- db1 = b2.add(b0);
- vm1 = da1.subtract(a1).multiply(db1.subtract(b1));
- da1 = da1.add(a1);
- db1 = db1.add(b1);
- v1 = da1.multiply(db1);
- v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply(
- db1.add(b2).shiftLeft(1).subtract(b0));
- vinf = a2.multiply(b2);
- // The algorithm requires two divisions by 2 and one by 3.
- // All divisions are known to be exact, that is, they do not produce
- // remainders, and all results are positive. The divisions by 2 are
- // implemented as right shifts which are relatively efficient, leaving
- // only an exact division by 3, which is done by a specialized
- // linear-time algorithm.
- t2 = v2.subtract(vm1).exactDivideBy3();
- tm1 = v1.subtract(vm1).shiftRight(1);
- t1 = v1.subtract(v0);
- t2 = t2.subtract(t1).shiftRight(1);
- t1 = t1.subtract(tm1).subtract(vinf);
- t2 = t2.subtract(vinf.shiftLeft(1));
- tm1 = tm1.subtract(t2);
- // Number of bits to shift left.
- int ss = k*32;
- BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
- if (a.signum != b.signum) {
- return result.negate();
- } else {
- return result;
- }
- }
-
- BigInteger getToomSlice(int lowerSize, int upperSize, int slice,
- int fullsize) {
- int start, end, sliceSize, len, offset;
- len = mag.size();
- offset = fullsize - len;
- if (slice == 0) {
- start = 0 - offset;
- end = upperSize - 1 - offset;
- } else {
- start = upperSize + (slice-1)*lowerSize - offset;
- end = start + lowerSize - 1;
- }
- if (start < 0) {
- start = 0;
- }
- if (end < 0) {
- return ZERO;
- }
- sliceSize = (end-start) + 1;
- if (sliceSize <= 0) {
- return ZERO;
- }
- // While performing Toom-Cook, all slices are positive and
- // the sign is adjusted when the const number is composed.
- if (start == 0 && sliceSize >= len) {
- return this->abs();
- }
- std::vector<int> intSlice(sliceSize);
- std::copy(mag.begin() + start,mag.begin() + start + sliceSize, intSlice.begin());
- return BigInteger(trustedStripLeadingZeroInts(intSlice), 1);
- }
-
- BigInteger exactDivideBy3() {
- int len = mag.size();
- std::vector<int> result(len);
- std::int64_t x, w, q, borrow;
- borrow = 0L;
- for (int i = len-1; i >= 0; i--) {
- x = (mag[i] & LONG_MASK);
- w = x - borrow;
- if (borrow > x) { // Did we make the number go negative?
- borrow = 1LL;
- } else {
- borrow = 0LL;
- }
- // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus,
- // the effect of this is to divide by 3 (mod 2^32).
- // This is much faster than division on most architectures.
- q = (w * 0xAAAAAAABL) & LONG_MASK;
- result[i] = (int) q;
- // Now check the borrow. The second check can of course be
- // eliminated if the first fails.
- if (q >= 0x55555556L) {
- borrow++;
- if (q >= 0xAAAAAAABL)
- borrow++;
- }
- }
- result = trustedStripLeadingZeroInts(result);
- return BigInteger(result, signum);
- }
-
- BigInteger getLower(int n) {
- int len = mag.size();
- if (len <= n) {
- return abs();
- }
- std::vector<int>lowerInts(n);
- std::copy(mag.begin() + (len - n), mag.end(), lowerInts.begin());
- return BigInteger(trustedStripLeadingZeroInts(lowerInts), 1);
- }
-
- BigInteger getUpper(int n) {
- int len = mag.length;
- if (len <= n) {
- return ZERO;
- }
- int upperLen = len - n;
- std::vector<int> upperInts(upperLen);
- std::copy(mag.begin(), mag.begin() + upperLen, upperInts);
- return BigInteger(trustedStripLeadingZeroInts(upperInts), 1);
- }
- // Squaring
-
- BigInteger square() {
- if (signum == 0) {
- return ZERO;
- }
- int len = mag.size();
- if (len < KARATSUBA_SQUARE_THRESHOLD) {
- std::vector<int> z = squareToLen(mag, len, null);
- return BigInteger(trustedStripLeadingZeroInts(z), 1);
- } else {
- if (len < TOOM_COOK_SQUARE_THRESHOLD) {
- return squareKaratsuba();
- } else {
- return squareToomCook3();
- }
- }
- }
-
- static std::vector<int> squareToLen(std::vector<int> x, int len, std::vector<int> z) {
- int zlen = len << 1;
- if (z == null || z.length < zlen)
- z = std::vector<int>(zlen);
- // Execute checks before calling intrinsified method.
- implSquareToLenChecks(x, len, z, zlen);
- return implSquareToLen(x, len, z, zlen);
- }
-
- static void implSquareToLenChecks(std::vector<int> x, int len, std::vector<int> z, int zlen){
- if (len < 1) {
- throw std::invalid_argument("invalid input length: " + len);
- }
- if (len > x.size()) {
- throw std::invalid_argument("input length out of bound: " +
- len + " > " + x.size());
- }
- if (len * 2 > z.size()) {
- throw std::invalid_argument("input length out of bound: " +
- (len * 2) + " > " + z.size());
- }
- if (zlen < 1) {
- throw std::invalid_argument("invalid input length: " + zlen);
- }
- if (zlen > z.size()) {
- throw std::invalid_argument("input length out of bound: " +
- len + " > " + z.size());
- }
- }
-
- static std::vector<int> implSquareToLen(std::vector<int> x, int len, std::vector<int> z, int zlen) {
- /*
- * The algorithm used here is adapted from Colin Plumb's C library.
- * Technique: Consider the partial products in the multiplication
- * of "abcde" by itself:
- *
- * a b c d e
- * * a b c d e
- * ==================
- * ae be ce de ee
- * ad bd cd dd de
- * ac bc cc cd ce
- * ab bb bc bd be
- * aa ab ac ad ae
- *
- * Note that everything above the main diagonal:
- * ae be ce de = (abcd) * e
- * ad bd cd = (abc) * d
- * ac bc = (ab) * c
- * ab = (a) * b
- *
- * is a copy of everything below the main diagonal:
- * de
- * cd ce
- * bc bd be
- * ab ac ad ae
- *
- * Thus, the sum is 2 * (off the diagonal) + diagonal.
- *
- * This is accumulated beginning with the diagonal (which
- * consist of the squares of the digits of the input), which is then
- * divided by two, the off-diagonal added, and multiplied by two
- * again. The low bit is simply a copy of the low bit of the
- * input, so it doesn't need special care.
- */
- // Store the squares, right shifted one bit (i.e., divided by 2)
- int lastProductLowWord = 0;
- for (int j=0, i=0; j < len; j++) {
- std::int64_t piece = (x[j] & LONG_MASK);
- uint64_t product = piece * piece;
- z[i++] = (lastProductLowWord << 31) | (int)(product >> 33);
- z[i++] = (int)(product >> 1);
- lastProductLowWord = (int)product;
- }
- // Add in off-diagonal sums
- for (int i=len, offset=1; i > 0; i--, offset+=2) {
- int t = x[i-1];
- t = mulAdd(z, x, offset, i-1, t);
- addOne(z, offset-1, i, t);
- }
- // Shift back up and set low bit
- primitiveLeftShift(z, zlen, 1);
- z[zlen-1] |= x[len-1] & 1;
- return z;
- }
-
- BigInteger squareKaratsuba() {
- int half = (mag.size()+1) / 2;
- BigInteger xl = getLower(half);
- BigInteger xh = getUpper(half);
- BigInteger xhs = xh.square(); // xhs = xh^2
- BigInteger xls = xl.square(); // xls = xl^2
- // xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2
- return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls);
- }
-
- BigInteger squareToomCook3() {
- int len = mag.size();
- // k is the size (in ints) of the lower-order slices.
- int k = (len+2)/3; // Equal to ceil(largest/3)
- // r is the size (in ints) of the highest-order slice.
- int r = len - 2*k;
- // Obtain slices of the numbers. a2 is the most significant
- // bits of the number, and a0 the least significant.
- BigInteger a0, a1, a2;
- a2 = getToomSlice(k, r, 0, len);
- a1 = getToomSlice(k, r, 1, len);
- a0 = getToomSlice(k, r, 2, len);
- BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1;
- v0 = a0.square();
- da1 = a2.add(a0);
- vm1 = da1.subtract(a1).square();
- da1 = da1.add(a1);
- v1 = da1.square();
- vinf = a2.square();
- v2 = da1.add(a2).shiftLeft(1).subtract(a0).square();
- // The algorithm requires two divisions by 2 and one by 3.
- // All divisions are known to be exact, that is, they do not produce
- // remainders, and all results are positive. The divisions by 2 are
- // implemented as right shifts which are relatively efficient, leaving
- // only a division by 3.
- // The division by 3 is done by an optimized algorithm for this case.
- t2 = v2.subtract(vm1).exactDivideBy3();
- tm1 = v1.subtract(vm1).shiftRight(1);
- t1 = v1.subtract(v0);
- t2 = t2.subtract(t1).shiftRight(1);
- t1 = t1.subtract(tm1).subtract(vinf);
- t2 = t2.subtract(vinf.shiftLeft(1));
- tm1 = tm1.subtract(t2);
- // Number of bits to shift left.
- int ss = k*32;
- return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0);
- }
- // Division
-
- BigInteger divide(BigInteger val) {
- if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
- mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
- return divideKnuth(val);
- } else {
- return divideBurnikelZiegler(val);
- }
- }
-
- BigInteger divideKnuth(BigInteger val) {
- MutableBigInteger q = MutableBigInteger(),
- a = MutableBigInteger(this->mag),
- b = MutableBigInteger(val.mag);
- a.divideKnuth(b, q, false);
- return q.toBigInteger(this->signum * val.signum);
- }
-
- std::vector<BigInteger> divideAndRemainder(BigInteger val) {
- if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD ||
- mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
- return divideAndRemainderKnuth(val);
- } else {
- return divideAndRemainderBurnikelZiegler(val);
- }
- }
-
- std::vector<BigInteger> divideAndRemainderKnuth(BigInteger val) {
- std::vector<BigInteger> result();
- MutableBigInteger q = MutableBigInteger(),
- a = MutableBigInteger(this->mag),
- b = MutableBigInteger(val.mag);
- MutableBigInteger r = a.divideKnuth(b, q);
- result[0] = q.toBigInteger(this->signum == val.signum ? 1 : -1);
- result[1] = r.toBigInteger(this->signum);
- return result;
- }
-
- BigInteger remainder(BigInteger val) {
- if (val.mag.size() < BURNIKEL_ZIEGLER_THRESHOLD ||
- mag.size() - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) {
- return remainderKnuth(val);
- } else {
- return remainderBurnikelZiegler(val);
- }
- }
-
- BigInteger remainderKnuth(BigInteger val) {
- MutableBigInteger q = MutableBigInteger(),
- a = MutableBigInteger(this->mag),
- b = MutableBigInteger(val.mag);
- return a.divideKnuth(b, q).toBigInteger(this->signum);
- }
-
- BigInteger divideBurnikelZiegler(BigInteger val) {
- return divideAndRemainderBurnikelZiegler(val)[0];
- }
-
- BigInteger remainderBurnikelZiegler(BigInteger val) {
- return divideAndRemainderBurnikelZiegler(val)[1];
- }
-
- std::vector<BigInteger> divideAndRemainderBurnikelZiegler(BigInteger val) {
- MutableBigInteger q = MutableBigInteger();
- MutableBigInteger r = MutableBigInteger(*this).divideAndRemainderBurnikelZiegler(MutableBigInteger(val), q);
- BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum);
- BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum);
- return std::vector<BigInteger> = {qBigInt, rBigInt};
- }
-
- BigInteger pow(int exponent) {
- assert(exponent > 0);
- if (signum == 0) {
- return (exponent == 0 ? ONE : this);
- }
- BigInteger partToSquare = this->abs();
- // Factor out powers of two from the base, as the exponentiation of
- // these can be done by left shifts only.
- // The remaining part can then be exponentiated faster. The
- // powers of two will be multiplied back at the end.
- int powersOfTwo = partToSquare.getLowestSetBit();
- long bitsToShift = (std::int64_t)powersOfTwo * exponent;
- if (bitsToShift > std::numeric_limits<int>::max()) {
- reportOverflow();
- }
- int remainingBits;
- // Factor the powers of two out quickly by shifting right, if needed.
- if (powersOfTwo > 0) {
- partToSquare = partToSquare.shiftRight(powersOfTwo);
- remainingBits = partToSquare.bitLength();
- if (remainingBits == 1) { // Nothing left but +/- 1?
- if (signum < 0 && (exponent&1) == 1) {
- return NEGATIVE_ONE.shiftLeft(powersOfTwo*exponent);
- } else {
- return ONE.shiftLeft(powersOfTwo*exponent);
- }
- }
- } else {
- remainingBits = partToSquare.bitLength();
- if (remainingBits == 1) { // Nothing left but +/- 1?
- if (signum < 0 && (exponent&1) == 1) {
- return NEGATIVE_ONE;
- } else {
- return ONE;
- }
- }
- }
- // This is a quick way to approximate the size of the result,
- // similar to doing log2[n] * exponent. This will give an upper bound
- // of how big the result can be, and which algorithm to use.
- long scaleFactor = (long)remainingBits * exponent;
- // Use slightly different algorithms for small and large operands.
- // See if the result will safely fit into a long. (Largest 2^63-1)
- if (partToSquare.mag.size() == 1 && scaleFactor <= 62) {
- // Small number algorithm. Everything fits into a long.
- int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1);
- long result = 1;
- long baseToPow2 = partToSquare.mag[0] & LONG_MASK;
- int workingExponent = exponent;
- // Perform exponentiation using repeated squaring trick
- while (workingExponent != 0) {
- if ((workingExponent & 1) == 1) {
- result = result * baseToPow2;
- }
- if ((workingExponent >>>= 1) != 0) {
- baseToPow2 = baseToPow2 * baseToPow2;
- }
- }
- // Multiply back the powers of two (quickly, by shifting left)
- if (powersOfTwo > 0) {
- if (bitsToShift + scaleFactor <= 62) { // Fits in long?
- return valueOf((result << bitsToShift) * newSign);
- } else {
- return valueOf(result*newSign).shiftLeft((int) bitsToShift);
- }
- }
- else {
- return valueOf(result*newSign);
- }
- } else {
- // Large number algorithm. This is basically identical to
- // the algorithm above, but calls multiply() and square()
- // which may use more efficient algorithms for large numbers.
- BigInteger answer = ONE;
- int workingExponent = exponent;
- // Perform exponentiation using repeated squaring trick
- while (workingExponent != 0) {
- if ((workingExponent & 1) == 1) {
- answer = answer.multiply(partToSquare);
- }
- if ((workingExponent >>>= 1) != 0) {
- partToSquare = partToSquare.square();
- }
- }
- // Multiply back the (exponentiated) powers of two (quickly,
- // by shifting left)
- if (powersOfTwo > 0) {
- answer = answer.shiftLeft(powersOfTwo*exponent);
- }
- if (signum < 0 && (exponent&1) == 1) {
- return answer.negate();
- } else {
- return answer;
- }
- }
- }
-
- BigInteger gcd(BigInteger val) {
- if (val.signum == 0)
- return this->abs();
- else if (this.signum == 0)
- return val.abs();
- MutableBigInteger a = MutableBigInteger(this);
- MutableBigInteger b = MutableBigInteger(val);
- MutableBigInteger result = a.hybridGCD(b);
- return result.toBigInteger(1);
- }
-
- static int bitLengthForInt(int n) {
- return 32 - Integer.numberOfLeadingZeros(n);
- }
-
- static std::vector<int> leftShift(std::vector<int> a, int len, unsigned int n) {
- int nInts = n >> 5;
- int nBits = n&0x1F;
- int bitsInHighWord = bitLengthForInt(a[0]);
- // If shift can be done without recopy, do so
- if (n <= (32 - bitsInHighWord)) {
- primitiveLeftShift(a, len, nBits);
- return a;
- } else { // Array must be resized
- if (nBits <= (32 - bitsInHighWord)) {
- std::vector<int> result(nInts + len);
- std::copy(a.begin(),a.begin() + len, result.begin());
- primitiveLeftShift(result, result.length, nBits);
- return result;
- } else {
- std::vector<int> resul(nInts + len + 1);
- std::copy(a.begin(), a.begin() + len, result.begin());
- primitiveRightShift(result, result.length, 32 - nBits);
- return result;
- }
- }
- }
- // shifts a up to len right n bits assumes no leading zeros, 0<n<32
- static void primitiveRightShift(std::vector<int> a, int len, int n) {
- int n2 = 32 - n;
- for (int i=len-1, c=a[i]; i > 0; i--) {
- unsigned int b = c;
- c = a[i-1];
- a[i] = (c << n2) | (b >> n);
- }
- a[0] = ((unsigned int)a[0]) >> n;
- }
- // shifts a up to len left n bits assumes no leading zeros, 0<=n<32
- static void primitiveLeftShift(std::vector<int> a, int len, int n) {
- if (len == 0 || n == 0)
- return;
- int n2 = 32 - n;
- for (unsigned int i=0, c=a[i], m=i+len-1; i < m; i++) {
- int b = c;
- c = a[i+1];
- a[i] = (b << n) | (c >> n2);
- }
- a[len-1] <<= n;
- }
-
- static int bitLength(std::vector<int> val, int len) {
- if (len == 0)
- return 0;
- return ((len - 1) << 5) + bitLengthForInt(val[0]);
- }
-
- BigInteger abs() {
- return (signum >= 0 ? this : this->negate());
- }
-
- BigInteger negate() {
- return BigInteger(this->mag, -this->signum);
- }
-
- int signum() {
- return this->signum;
- }
- // Modular Arithmetic Operations
-
- BigInteger mod(BigInteger m) {
- assert(m.signum > 0)
- BigInteger result = this->remainder(m);
- return (result.signum >= 0 ? result : result.add(m));
- }
-
- BigInteger modPow(BigInteger exponent, BigInteger m) {
- assert(m.signum > 0)
- // Trivial cases
- if (exponent.signum == 0)
- return (m.equals(ONE) ? ZERO : ONE);
- if (this.equals(ONE))
- return (m.equals(ONE) ? ZERO : ONE);
- if (this.equals(ZERO) && exponent.signum >= 0)
- return ZERO;
- if (this.equals(negConst[1]) && (!exponent.testBit(0)))
- return (m.equals(ONE) ? ZERO : ONE);
- boolean invertResult;
- if ((invertResult = (exponent.signum < 0)))
- exponent = exponent.negate();
- BigInteger base = (this->signum < 0 || this->compareTo(m) >= 0
- ? this->mod(m) : this);
- BigInteger result;
- if (m.testBit(0)) { // odd modulus
- result = base.oddModPow(exponent, m);
- } else {
- /*
- * Even modulus. Tear it into an "odd part" (m1) and power of two
- * (m2), exponentiate mod m1, manually exponentiate mod m2, and
- * use Chinese Remainder Theorem to combine results.
- */
- // Tear m apart into odd part (m1) and power of 2 (m2)
- int p = m.getLowestSetBit(); // Max pow of 2 that divides m
- BigInteger m1 = m.shiftRight(p); // m/2**p
- BigInteger m2 = ONE.shiftLeft(p); // 2**p
- // Calculate new base from m1
- BigInteger base2 = (this->signum < 0 || this->compareTo(m1) >= 0
- ? this->mod(m1) : this);
- // Caculate (base ** exponent) mod m1.
- BigInteger a1 = (m1.equals(ONE) ? ZERO :
- base2.oddModPow(exponent, m1));
- // Calculate (this ** exponent) mod m2
- BigInteger a2 = base.modPow2(exponent, p);
- // Combine results using Chinese Remainder Theorem
- BigInteger y1 = m2.modInverse(m1);
- BigInteger y2 = m1.modInverse(m2);
- if (m.mag.length < MAX_MAG_LENGTH / 2) {
- result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
- } else {
- MutableBigInteger t1;
- new MutableBigInteger(a1.multiply(m2)).multiply(MutableBigInteger(y1), t1);
- MutableBigInteger t2;
- new MutableBigInteger(a2.multiply(m1)).multiply(MutableBigInteger(y2), t2);
- t1.add(t2);
- MutableBigInteger q;
- result = t1.divide(MutableBigInteger(m), q).toBigInteger();
- }
- }
- return (invertResult ? result.modInverse(m) : result);
- }
- // Montgomery multiplication. These are wrappers for
- // implMontgomeryXX routines which are expected to be replaced by
- // virtual machine intrinsics. We don't use the intrinsics for
- // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be
- // larger than any reasonable crypto key.
- static std::vector<int> montgomeryMultiply(std::vector<int> a, std::vector<int> b, std::vector<int> n, int len, long inv,
- std::vector<int> product) {
- implMontgomeryMultiplyChecks(a, b, n, len, product);
- if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
- // Very long argument: do not use an intrinsic
- product = multiplyToLen(a, len, b, len, product);
- return montReduce(product, n, len, (int)inv);
- } else {
- return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len));
- }
- }
- static std::vector<int> montgomerySquare(std::vector<int> a, std::vector<int> n, int len, std::int64_t inv,
- std::vector<int> product) {
- implMontgomeryMultiplyChecks(a, a, n, len, product);
- if (len > MONTGOMERY_INTRINSIC_THRESHOLD) {
- // Very long argument: do not use an intrinsic
- product = squareToLen(a, len, product);
- return montReduce(product, n, len, (int)inv);
- } else {
- return implMontgomerySquare(a, n, len, inv, materialize(product, len));
- }
- }
- // Range-check everything.
- static void implMontgomeryMultiplyChecks
- (std::vector<int> a, std::vector<int> b, std::vector<int> n, int len, std::vector<int> product) {
- if (len % 2 != 0) {
- throw std::invalid_argument("input array length must be even: " + std::to_string(len));
- }
- if (len < 1) {
- throw std::invalid_argument("invalid input length: " + std::to_string(len));
- }
- if (len > a.size() ||
- len > b.size() ||
- len > n.size() ||
- (len > product.size())) {
- throw std::invalid_argument("input array length out of bound: " + len);
- }
- }
- // Make sure that the int array z (which is expected to contain
- // the result of a Montgomery multiplication) is present and
- // sufficiently large.
- static std::vector<int> materialize(std::vector<int> z, int len) {
- if (z.size() < len)
- z = std::vector<int>(len);
- return z;
- }
- // These methods are intended to be be replaced by virtual machine
- // intrinsics.
- static std::vector<int> implMontgomeryMultiply(std::vector<int> a, std::vector<int> b, std::vector<int> n, int len,
- std::int64_t inv, std::vector<int> product) {
- product = multiplyToLen(a, len, b, len, product);
- return montReduce(product, n, len, (int)inv);
- }
- static std::vector<int> implMontgomerySquare(std::vector<int> a, std::vector<int> n, int len,
- std::int64_t inv, std::vector<int> product) {
- product = squareToLen(a, len, product);
- return montReduce(product, n, len, (int)inv);
- }
- static std::vector<int> bnExpModThreshTable = {7, 25, 81, 241, 673, 1793,
- std::numeric_limits<int>::max()}; // Sentinel
-
- BigInteger oddModPow(BigInteger y, BigInteger z) {
- /*
- * The algorithm is adapted from Colin Plumb's C library.
- *
- * The window algorithm:
- * The idea is to keep a running product of b1 = n^(high-order bits of exp)
- * and then keep appending exponent bits to it. The following patterns
- * apply to a 3-bit window (k = 3):
- * To append 0: square
- * To append 1: square, multiply by n^1
- * To append 10: square, multiply by n^1, square
- * To append 11: square, square, multiply by n^3
- * To append 100: square, multiply by n^1, square, square
- * To append 101: square, square, square, multiply by n^5
- * To append 110: square, square, multiply by n^3, square
- * To append 111: square, square, square, multiply by n^7
- *
- * Since each pattern involves only one multiply, the longer the pattern
- * the better, except that a 0 (no multiplies) can be appended directly.
- * We precompute a table of odd powers of n, up to 2^k, and can then
- * multiply k bits of exponent at a time. Actually, assuming random
- * exponents, there is on average one zero bit between needs to
- * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
- * 1/8 of the time, there's 2, 1/32 of the time, there's 3, etc.), so
- * you have to do one multiply per k+1 bits of exponent.
- *
- * The loop walks down the exponent, squaring the result buffer as
- * it goes. There is a wbits+1 bit lookahead buffer, buf, that is
- * filled with the upcoming exponent bits. (What is read after the
- * end of the exponent is unimportant, but it is filled with zero here.)
- * When the most-significant bit of this buffer becomes set, i.e.
- * (buf & tblmask) != 0, we have to decide what pattern to multiply
- * by, and when to do it. We decide, remember to do it in future
- * after a suitable number of squarings have passed (e.g. a pattern
- * of "100" in the buffer requires that we multiply by n^1 immediately;
- * a pattern of "110" calls for multiplying by n^3 after one more
- * squaring), clear the buffer, and continue.
- *
- * When we start, there is one more optimization: the result buffer
- * is implcitly one, so squaring it or multiplying by it can be
- * optimized away. Further, if we start with a pattern like "100"
- * in the lookahead window, rather than placing n into the buffer
- * and then starting to square it, we have already computed n^2
- * to compute the odd-powers table, so we can place that into
- * the buffer and save a squaring.
- *
- * This means that if you have a k-bit window, to compute n^z,
- * where z is the high k bits of the exponent, 1/2 of the time
- * it requires no squarings. 1/4 of the time, it requires 1
- * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
- * And the remaining 1/2^(k-1) of the time, the top k bits are a
- * 1 followed by k-1 0 bits, so it again only requires k-2
- * squarings, not k-1. The average of these is 1. Add that
- * to the one squaring we have to do to compute the table,
- * and you'll see that a k-bit window saves k-2 squarings
- * as well as reducing the multiplies. (It actually doesn't
- * hurt in the case k = 1, either.)
- */
- // Special case for exponent of one
- if (y.equals(ONE))
- return *this;
- // Special case for base of zero
- if (signum == 0)
- return ZERO;
- std::vector<int> base = mag.clone();
- std::vector<int> exp = y.mag;
- std::vector<int> mod = z.mag;
- int modLen = mod.size();
- // Make modLen even. It is conventional to use a cryptographic
- // modulus that is 512, 768, 1024, or 2048 bits, so this code
- // will not normally be executed. However, it is necessary for
- // the correct functioning of the HotSpot intrinsics.
- if ((modLen & 1) != 0) {
- std::vector<int> x(modlen + 1);
- std::copy(mod.begin(), mod.begin() + modLen, x.begin());
- mod = std::move(x);
- modLen++;
- }
- // Select an appropriate window size
- int wbits = 0;
- int ebits = bitLength(exp, exp.size());
- // if exponent is 65537 (0x10001), use minimum window size
- if ((ebits != 17) || (exp[0] != 65537)) {
- while (ebits > bnExpModThreshTable[wbits]) {
- wbits++;
- }
- }
- // Calculate appropriate table size
- int tblmask = 1 << wbits;
- // Allocate table for precomputed odd powers of base in Montgomery form
- std::vector<std::vector<int>> table(tblmask);// = new int[tblmask][];
- for (int i=0; i < tblmask; i++)
- table[i] = std::vector<int>(modLen);
- // Compute the modular inverse of the least significant 64-bit
- // digit of the modulus
- std::int64_t n0 = (mod[modLen-1] & LONG_MASK) + ((mod[modLen-2] & LONG_MASK) << 32);
- std::int64_t inv = -MutableBigInteger.inverseMod64(n0);
- // Convert base to Montgomery form
- std::vector<int> a = leftShift(base, base.length, modLen << 5);
- MutableBigInteger q = MutableBigInteger(),
- a2 = MutableBigInteger(a),
- b2 = MutableBigInteger(mod);
- b2.normalize(); // MutableBigInteger.divide() assumes that its
- // divisor is in normal form.
- MutableBigInteger r= a2.divide(b2, q);
- table[0] = r.toIntArray();
- // Pad table[0] with leading zeros so its length is at least modLen
- if (table[0].size() < modLen) {
- int offset = modLen - table[0].size();
- std::vector<int> t2(modLen);// = new int[modLen];
- std::copy(table[0].begin(),table[0].end(), t2.begin());
- table[0] = t2;
- }
- // Set b to the square of the base
- std::vector<int> b = montgomerySquare(table[0], mod, modLen, inv, null);
- // Set t to high half of b
- std::vector<int> t(b.begin(), b.begin() + modLen);
- // Fill in the table with odd powers of the base
- for (int i=1; i < tblmask; i++) {
- table[i] = montgomeryMultiply(t, table[i-1], mod, modLen, inv, null);
- }
- // Pre load the window that slides over the exponent
- unsigned int bitpos = 1 << ((ebits-1) & (32-1));
- int buf = 0;
- int elen = exp.length;
- int eIndex = 0;
- for (int i = 0; i <= wbits; i++) {
- buf = (buf << 1) | (((exp[eIndex] & bitpos) != 0)?1:0);
- bitpos >>>= 1;
- if (bitpos == 0) {
- eIndex++;
- bitpos = 1 << (32-1);
- elen--;
- }
- }
- int multpos = ebits;
- // The first iteration, which is hoisted out of the main loop
- ebits--;
- boolean isone = true;
- multpos = ebits - wbits;
- while ((buf & 1) == 0) {
- buf >>>= 1;
- multpos++;
- }
- int[] mult = table[buf >>> 1];
- buf = 0;
- if (multpos == ebits)
- isone = false;
- // The main loop
- while (true) {
- ebits--;
- // Advance the window
- buf <<= 1;
- if (elen != 0) {
- buf |= ((exp[eIndex] & bitpos) != 0) ? 1 : 0;
- bitpos >>>= 1;
- if (bitpos == 0) {
- eIndex++;
- bitpos = 1 << (32-1);
- elen--;
- }
- }
- // Examine the window for pending multiplies
- if ((buf & tblmask) != 0) {
- multpos = ebits - wbits;
- while ((buf & 1) == 0) {
- buf >>>= 1;
- multpos++;
- }
- mult = table[buf >>> 1];
- buf = 0;
- }
- // Perform multiply
- if (ebits == multpos) {
- if (isone) {
- b = mult.clone();
- isone = false;
- } else {
- t = b;
- a = montgomeryMultiply(t, mult, mod, modLen, inv, a);
- t = a; a = b; b = t;
- }
- }
- // Check if done
- if (ebits == 0)
- break;
- // Square the input
- if (!isone) {
- t = b;
- a = montgomerySquare(t, mod, modLen, inv, a);
- t = a; a = b; b = t;
- }
- }
- // Convert result out of Montgomery form and return
- int[] t2 = new int[2*modLen];
- System.arraycopy(b, 0, t2, modLen, modLen);
- b = montReduce(t2, mod, modLen, (int)inv);
- t2 = Arrays.copyOf(b, modLen);
- return new BigInteger(1, t2);
- }
-
- static int[] montReduce(int[] n, int[] mod, int mlen, int inv) {
- int c=0;
- int len = mlen;
- int offset=0;
- do {
- int nEnd = n[n.length-1-offset];
- int carry = mulAdd(n, mod, offset, mlen, inv * nEnd);
- c += addOne(n, offset, mlen, carry);
- offset++;
- } while (--len > 0);
- while (c > 0)
- c += subN(n, mod, mlen);
- while (intArrayCmpToLen(n, mod, mlen) >= 0)
- subN(n, mod, mlen);
- return n;
- }
- /*
- * Returns -1, 0 or +1 as big-endian unsigned int array arg1 is less than,
- * equal to, or greater than arg2 up to length len.
- */
- static int intArrayCmpToLen(int[] arg1, int[] arg2, int len) {
- for (int i=0; i < len; i++) {
- long b1 = arg1[i] & LONG_MASK;
- long b2 = arg2[i] & LONG_MASK;
- if (b1 < b2)
- return -1;
- if (b1 > b2)
- return 1;
- }
- return 0;
- }
-
- static int subN(int[] a, int[] b, int len) {
- long sum = 0;
- while (--len >= 0) {
- sum = (a[len] & LONG_MASK) -
- (b[len] & LONG_MASK) + (sum >> 32);
- a[len] = (int)sum;
- }
- return (int)(sum >> 32);
- }
-
- static int mulAdd(int[] out, int[] in, int offset, int len, int k) {
- implMulAddCheck(out, in, offset, len, k);
- return implMulAdd(out, in, offset, len, k);
- }
-
- static void implMulAddCheck(int[] out, int[] in, int offset, int len, int k) {
- if (len > in.length) {
- throw new IllegalArgumentException("input length is out of bound: " + len + " > " + in.length);
- }
- if (offset < 0) {
- throw new IllegalArgumentException("input offset is invalid: " + offset);
- }
- if (offset > (out.length - 1)) {
- throw new IllegalArgumentException("input offset is out of bound: " + offset + " > " + (out.length - 1));
- }
- if (len > (out.length - offset)) {
- throw new IllegalArgumentException("input len is out of bound: " + len + " > " + (out.length - offset));
- }
- }
-
- static int implMulAdd(int[] out, int[] in, int offset, int len, int k) {
- long kLong = k & LONG_MASK;
- long carry = 0;
- offset = out.length-offset - 1;
- for (int j=len-1; j >= 0; j--) {
- long product = (in[j] & LONG_MASK) * kLong +
- (out[offset] & LONG_MASK) + carry;
- out[offset--] = (int)product;
- carry = product >>> 32;
- }
- return (int)carry;
- }
-
- static int addOne(int[] a, int offset, int mlen, int carry) {
- offset = a.length-1-mlen-offset;
- long t = (a[offset] & LONG_MASK) + (carry & LONG_MASK);
- a[offset] = (int)t;
- if ((t >>> 32) == 0)
- return 0;
- while (--mlen >= 0) {
- if (--offset < 0) { // Carry out of number
- return 1;
- } else {
- a[offset]++;
- if (a[offset] != 0)
- return 0;
- }
- }
- return 1;
- }
-
- BigInteger modPow2(BigInteger exponent, int p) {
- /*
- * Perform exponentiation using repeated squaring trick, chopping off
- * high order bits as indicated by modulus.
- */
- BigInteger result = ONE;
- BigInteger baseToPow2 = this.mod2(p);
- int expOffset = 0;
- int limit = exponent.bitLength();
- if (this.testBit(0))
- limit = (p-1) < limit ? (p-1) : limit;
- while (expOffset < limit) {
- if (exponent.testBit(expOffset))
- result = result.multiply(baseToPow2).mod2(p);
- expOffset++;
- if (expOffset < limit)
- baseToPow2 = baseToPow2.square().mod2(p);
- }
- return result;
- }
-
- BigInteger mod2(int p) {
- if (bitLength() <= p)
- return this;
- // Copy remaining ints of mag
- int numInts = (p + 31) >>> 5;
- int[] mag = new int[numInts];
- System.arraycopy(this.mag, (this.mag.length - numInts), mag, 0, numInts);
- // Mask out any excess bits
- int excessBits = (numInts << 5) - p;
- mag[0] &= (1L << (32-excessBits)) - 1;
- return (mag[0] == 0 ? new BigInteger(1, mag) : new BigInteger(mag, 1));
- }
-
- BigInteger modInverse(BigInteger m) {
- if (m.signum != 1)
- throw new ArithmeticException("BigInteger: modulus not positive");
- if (m.equals(ONE))
- return ZERO;
- // Calculate (this mod m)
- BigInteger modVal = this;
- if (signum < 0 || (this.compareMagnitude(m) >= 0))
- modVal = this.mod(m);
- if (modVal.equals(ONE))
- return ONE;
- MutableBigInteger a = new MutableBigInteger(modVal);
- MutableBigInteger b = new MutableBigInteger(m);
- MutableBigInteger result = a.mutableModInverse(b);
- return result.toBigInteger(1);
- }
- // Shift Operations
-
- BigInteger shiftLeft(int n) {
- if (signum == 0)
- return ZERO;
- if (n > 0) {
- return new BigInteger(shiftLeft(mag, n), signum);
- } else if (n == 0) {
- return this;
- } else {
- // Possible int overflow in (-n) is not a trouble,
- // because shiftRightImpl considers its argument unsigned
- return shiftRightImpl(-n);
- }
- }
-
- static int[] shiftLeft(int[] mag, int n) {
- int nInts = n >>> 5;
- int nBits = n & 0x1f;
- int magLen = mag.length;
- int newMag[] = null;
- if (nBits == 0) {
- newMag = new int[magLen + nInts];
- System.arraycopy(mag, 0, newMag, 0, magLen);
- } else {
- int i = 0;
- int nBits2 = 32 - nBits;
- int highBits = mag[0] >>> nBits2;
- if (highBits != 0) {
- newMag = new int[magLen + nInts + 1];
- newMag[i++] = highBits;
- } else {
- newMag = new int[magLen + nInts];
- }
- int j=0;
- while (j < magLen-1)
- newMag[i++] = mag[j++] << nBits | mag[j] >>> nBits2;
- newMag[i] = mag[j] << nBits;
- }
- return newMag;
- }
-
- BigInteger shiftRight(int n) {
- if (signum == 0)
- return ZERO;
- if (n > 0) {
- return shiftRightImpl(n);
- } else if (n == 0) {
- return this;
- } else {
- return BigInteger(shiftLeft(mag, -n), signum);
- }
- }
-
- BigInteger shiftRightImpl(int n) {
- int nInts = n >>> 5;
- int nBits = n & 0x1f;
- int magLen = mag.length;
- int newMag[] = null;
- // Special case: entire contents shifted off the end
- if (nInts >= magLen)
- return (signum >= 0 ? ZERO : negConst[1]);
- if (nBits == 0) {
- int newMagLen = magLen - nInts;
- newMag = Arrays.copyOf(mag, newMagLen);
- } else {
- int i = 0;
- int highBits = mag[0] >>> nBits;
- if (highBits != 0) {
- newMag = new int[magLen - nInts];
- newMag[i++] = highBits;
- } else {
- newMag = new int[magLen - nInts -1];
- }
- int nBits2 = 32 - nBits;
- int j=0;
- while (j < magLen - nInts - 1)
- newMag[i++] = (mag[j++] << nBits2) | (mag[j] >>> nBits);
- }
- if (signum < 0) {
- // Find out whether any one-bits were shifted off the end.
- boolean onesLost = false;
- for (int i=magLen-1, j=magLen-nInts; i >= j && !onesLost; i--)
- onesLost = (mag[i] != 0);
- if (!onesLost && nBits != 0)
- onesLost = (mag[magLen - nInts - 1] << (32 - nBits) != 0);
- if (onesLost)
- newMag = javaIncrement(newMag);
- }
- return new BigInteger(newMag, signum);
- }
- int[] javaIncrement(int[] val) {
- int lastSum = 0;
- for (int i=val.length-1; i >= 0 && lastSum == 0; i--)
- lastSum = (val[i] += 1);
- if (lastSum == 0) {
- val = new int[val.length+1];
- val[0] = 1;
- }
- return val;
- }
- // Bitwise Operations
-
- BigInteger and(BigInteger val) {
- int[] result = new int[Math.max(intLength(), val.intLength())];
- for (int i=0; i < result.length; i++)
- result[i] = (getInt(result.length-i-1)
- & val.getInt(result.length-i-1));
- return valueOf(result);
- }
-
- BigInteger or(BigInteger val) {
- int[] result = new int[Math.max(intLength(), val.intLength())];
- for (int i=0; i < result.length; i++)
- result[i] = (getInt(result.length-i-1)
- | val.getInt(result.length-i-1));
- return valueOf(result);
- }
-
- BigInteger xor(BigInteger val) {
- int[] result = new int[Math.max(intLength(), val.intLength())];
- for (int i=0; i < result.length; i++)
- result[i] = (getInt(result.length-i-1)
- ^ val.getInt(result.length-i-1));
- return valueOf(result);
- }
-
- BigInteger not() {
- int[] result = new int[intLength()];
- for (int i=0; i < result.length; i++)
- result[i] = ~getInt(result.length-i-1);
- return valueOf(result);
- }
-
- BigInteger andNot(BigInteger val) {
- int[] result = new int[Math.max(intLength(), val.intLength())];
- for (int i=0; i < result.length; i++)
- result[i] = (getInt(result.length-i-1)
- & ~val.getInt(result.length-i-1));
- return valueOf(result);
- }
- // Single Bit Operations
-
- boolean testBit(int n) {
- if (n < 0)
- throw new ArithmeticException("Negative bit address");
- return (getInt(n >>> 5) & (1 << (n & 31))) != 0;
- }
-
- BigInteger setBit(int n) {
- if (n < 0)
- throw new ArithmeticException("Negative bit address");
- int intNum = n >>> 5;
- int[] result = new int[Math.max(intLength(), intNum+2)];
- for (int i=0; i < result.length; i++)
- result[result.length-i-1] = getInt(i);
- result[result.length-intNum-1] |= (1 << (n & 31));
- return valueOf(result);
- }
-
- BigInteger clearBit(int n) {
- if (n < 0)
- throw new ArithmeticException("Negative bit address");
- int intNum = n >>> 5;
- int[] result = new int[Math.max(intLength(), ((n + 1) >>> 5) + 1)];
- for (int i=0; i < result.length; i++)
- result[result.length-i-1] = getInt(i);
- result[result.length-intNum-1] &= ~(1 << (n & 31));
- return valueOf(result);
- }
-
- BigInteger flipBit(int n) {
- if (n < 0)
- throw new ArithmeticException("Negative bit address");
- int intNum = n >>> 5;
- int[] result = new int[Math.max(intLength(), intNum+2)];
- for (int i=0; i < result.length; i++)
- result[result.length-i-1] = getInt(i);
- result[result.length-intNum-1] ^= (1 << (n & 31));
- return valueOf(result);
- }
-
- int getLowestSetBit() {
- if (lsb == -2) { // lowestSetBit not initialized yet
- lsb = 0;
- if (signum == 0) {
- lsb -= 1;
- } else {
- // Search for lowest order nonzero int
- int i,b;
- for (i=0; (b = getInt(i)) == 0; i++)
- ;
- lsb += (i << 5) + Integer.numberOfTrailingZeros(b);
- }
- lowestSetBit = lsb + 2;
- }
- return lsb;
- }
- // Miscellaneous Bit Operations
-
- int bitLength() {
- if (n == -1) { // bitLength not initialized yet
- int[] m = mag;
- int len = m.length;
- if (len == 0) {
- n = 0; // offset by one to initialize
- } else {
- // Calculate the bit length of the magnitude
- int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]);
- if (signum < 0) {
- // Check if magnitude is a power of two
- boolean pow2 = (Integer.bitCount(mag[0]) == 1);
- for (int i=1; i< len && pow2; i++)
- pow2 = (mag[i] == 0);
- n = (pow2 ? magBitLength -1 : magBitLength);
- } else {
- n = magBitLength;
- }
- }
- bitLength = n + 1;
- }
- return n;
- }
-
- int bitCount() {
- if (bc == -1) { // bitCount not initialized yet
- bc = 0; // offset by one to initialize
- // Count the bits in the magnitude
- for (int i=0; i < mag.length; i++)
- bc += Integer.bitCount(mag[i]);
- if (signum < 0) {
- // Count the trailing zeros in the magnitude
- int magTrailingZeroCount = 0, j;
- for (j=mag.length-1; mag[j] == 0; j--)
- magTrailingZeroCount += 32;
- magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]);
- bc += magTrailingZeroCount - 1;
- }
- bitCount = bc + 1;
- }
- return bc;
- }
- // Primality Testing
-
- boolean isProbablePrime(int certainty) {
- if (certainty <= 0)
- return true;
- BigInteger w = this.abs();
- if (w.equals(TWO))
- return true;
- if (!w.testBit(0) || w.equals(ONE))
- return false;
- return w.primeToCertainty(certainty, null);
- }
- // Comparison Operations
-
- int compareTo(BigInteger val) {
- if (signum == val.signum) {
- switch (signum) {
- case 1:
- return compareMagnitude(val);
- case -1:
- return val.compareMagnitude(this);
- default:
- return 0;
- }
- }
- return signum > val.signum ? 1 : -1;
- }
-
- const int compareMagnitude(BigInteger val) {
- int[] m1 = mag;
- int len1 = m1.length;
- int[] m2 = val.mag;
- int len2 = m2.length;
- if (len1 < len2)
- return -1;
- if (len1 > len2)
- return 1;
- for (int i = 0; i < len1; i++) {
- int a = m1[i];
- int b = m2[i];
- if (a != b)
- return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1;
- }
- return 0;
- }
-
- const int compareMagnitude(long val) {
- assert val != Long.MIN_VALUE;
- int[] m1 = mag;
- int len = m1.length;
- if (len > 2) {
- return 1;
- }
- if (val < 0) {
- val = -val;
- }
- int highWord = (int)(val >>> 32);
- if (highWord == 0) {
- if (len < 1)
- return -1;
- if (len > 1)
- return 1;
- int a = m1[0];
- int b = (int)val;
- if (a != b) {
- return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
- }
- return 0;
- } else {
- if (len < 2)
- return -1;
- int a = m1[0];
- int b = highWord;
- if (a != b) {
- return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
- }
- a = m1[1];
- b = (int)val;
- if (a != b) {
- return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1;
- }
- return 0;
- }
- }
-
- boolean equals(Object x) {
- // This test is just an optimization, which may or may not help
- if (x == this)
- return true;
- if (!(x instanceof BigInteger))
- return false;
- BigInteger xInt = (BigInteger) x;
- if (xInt.signum != signum)
- return false;
- int[] m = mag;
- int len = m.length;
- int[] xm = xInt.mag;
- if (len != xm.length)
- return false;
- for (int i = 0; i < len; i++)
- if (xm[i] != m[i])
- return false;
- return true;
- }
-
- BigInteger min(BigInteger val) {
- return (compareTo(val) < 0 ? this : val);
- }
-
- BigInteger max(BigInteger val) {
- return (compareTo(val) > 0 ? this : val);
- }
- // Hash Function
-
- int hashCode() {
- int hashCode = 0;
- for (int i=0; i < mag.length; i++)
- hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK));
- return hashCode * signum;
- }
-
- String toString(int radix) {
- if (signum == 0)
- return "0";
- if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
- radix = 10;
- // If it's small enough, use smallToString.
- if (mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD)
- return smallToString(radix);
- // Otherwise use recursive toString, which requires positive arguments.
- // The results will be concatenated into this StringBuilder
- StringBuilder sb = new StringBuilder();
- if (signum < 0) {
- toString(this.negate(), sb, radix, 0);
- sb.insert(0, '-');
- }
- else
- toString(this, sb, radix, 0);
- return sb.toString();
- }
-
- String smallToString(int radix) {
- if (signum == 0) {
- return "0";
- }
- // Compute upper bound on number of digit groups and allocate space
- int maxNumDigitGroups = (4*mag.length + 6)/7;
- String digitGroup[] = new String[maxNumDigitGroups];
- // Translate number to string, a digit group at a time
- BigInteger tmp = this.abs();
- int numGroups = 0;
- while (tmp.signum != 0) {
- BigInteger d = longRadix[radix];
- MutableBigInteger q = new MutableBigInteger(),
- a = new MutableBigInteger(tmp.mag),
- b = new MutableBigInteger(d.mag);
- MutableBigInteger r = a.divide(b, q);
- BigInteger q2 = q.toBigInteger(tmp.signum * d.signum);
- BigInteger r2 = r.toBigInteger(tmp.signum * d.signum);
- digitGroup[numGroups++] = Long.toString(r2.longValue(), radix);
- tmp = q2;
- }
- // Put sign (if any) and first digit group into result buffer
- StringBuilder buf = new StringBuilder(numGroups*digitsPerLong[radix]+1);
- if (signum < 0) {
- buf.append('-');
- }
- buf.append(digitGroup[numGroups-1]);
- // Append remaining digit groups padded with leading zeros
- for (int i=numGroups-2; i >= 0; i--) {
- // Prepend (any) leading zeros for this digit group
- int numLeadingZeros = digitsPerLong[radix]-digitGroup[i].length();
- if (numLeadingZeros != 0) {
- buf.append(zeros[numLeadingZeros]);
- }
- buf.append(digitGroup[i]);
- }
- return buf.toString();
- }
-
- static void toString(BigInteger u, StringBuilder sb, int radix,
- int digits) {
- /* If we're smaller than a certain threshold, use the smallToString
- method, padding with leading zeroes when necessary. */
- if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) {
- String s = u.smallToString(radix);
- // Pad with internal zeros if necessary.
- // Don't pad if we're at the beginning of the string.
- if ((s.length() < digits) && (sb.length() > 0)) {
- for (int i=s.length(); i < digits; i++) { // May be a faster way to
- sb.append('0'); // do this?
- }
- }
- sb.append(s);
- return;
- }
- int b, n;
- b = u.bitLength();
- // Calculate a value for n in the equation radix^(2^n) = u
- // and subtract 1 from that value. This is used to find the
- // cache index that contains the best value to divide u.
- n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0);
- BigInteger v = getRadixConversionCache(radix, n);
- BigInteger[] results;
- results = u.divideAndRemainder(v);
- int expectedDigits = 1 << n;
- // Now recursively build the two halves of each number.
- toString(results[0], sb, radix, digits-expectedDigits);
- toString(results[1], sb, radix, expectedDigits);
- }
-
- static BigInteger getRadixConversionCache(int radix, int exponent) {
- BigInteger[] cacheLine = powerCache[radix]; // volatile read
- if (exponent < cacheLine.length) {
- return cacheLine[exponent];
- }
- int oldLength = cacheLine.length;
- cacheLine = Arrays.copyOf(cacheLine, exponent + 1);
- for (int i = oldLength; i <= exponent; i++) {
- cacheLine[i] = cacheLine[i - 1].pow(2);
- }
- BigInteger[][] pc = powerCache; // volatile read again
- if (exponent >= pc[radix].length) {
- pc = pc.clone();
- pc[radix] = cacheLine;
- powerCache = pc; // volatile write, publish
- }
- return cacheLine[exponent];
- }
- /* zero[i] is a string of i consecutive zeros. */
- static String zeros[] = new String[64];
- static {
- zeros[63] =
- "000000000000000000000000000000000000000000000000000000000000000";
- for (int i=0; i < 63; i++)
- zeros[i] = zeros[63].substring(0, i);
- }
-
- String toString() {
- return toString(10);
- }
-
- byte[] toByteArray() {
- int byteLen = bitLength()/8 + 1;
- byte[] byteArray = new byte[byteLen];
- for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) {
- if (bytesCopied == 4) {
- nextInt = getInt(intIndex++);
- bytesCopied = 1;
- } else {
- nextInt >>>= 8;
- bytesCopied++;
- }
- byteArray[i] = (byte)nextInt;
- }
- return byteArray;
- }
-
- int intValue() {
- int result = 0;
- result = getInt(0);
- return result;
- }
-
- long longValue() {
- long result = 0;
- for (int i=1; i >= 0; i--)
- result = (result << 32) + (getInt(i) & LONG_MASK);
- return result;
- }
-
- float floatValue() {
- if (signum == 0) {
- return 0.0f;
- }
- int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
- // exponent == floor(log2(abs(this)))
- if (exponent < Long.SIZE - 1) {
- return longValue();
- } else if (exponent > Float.MAX_EXPONENT) {
- return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY;
- }
- /*
- * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
- * one bit. To make rounding easier, we pick out the top
- * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
- * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
- * bits, and signifFloor the top SIGNIFICAND_WIDTH.
- *
- * It helps to consider the real number signif = abs(this) *
- * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
- */
- int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH;
- int twiceSignifFloor;
- // twiceSignifFloor will be == abs().shiftRight(shift).intValue()
- // We do the shift into an int directly to improve performance.
- int nBits = shift & 0x1f;
- int nBits2 = 32 - nBits;
- if (nBits == 0) {
- twiceSignifFloor = mag[0];
- } else {
- twiceSignifFloor = mag[0] >>> nBits;
- if (twiceSignifFloor == 0) {
- twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits);
- }
- }
- int signifFloor = twiceSignifFloor >> 1;
- signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit
- /*
- * We round up if either the fractional part of signif is strictly
- * greater than 0.5 (which is true if the 0.5 bit is set and any lower
- * bit is set), or if the fractional part of signif is >= 0.5 and
- * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
- * are set). This is equivalent to the desired HALF_EVEN rounding.
- */
- boolean increment = (twiceSignifFloor & 1) != 0
- && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
- int signifRounded = increment ? signifFloor + 1 : signifFloor;
- int bits = ((exponent + FloatConsts.EXP_BIAS))
- << (FloatConsts.SIGNIFICAND_WIDTH - 1);
- bits += signifRounded;
- /*
- * If signifRounded == 2^24, we'd need to set all of the significand
- * bits to zero and add 1 to the exponent. This is exactly the behavior
- * we get from just adding signifRounded to bits directly. If the
- * exponent is Float.MAX_EXPONENT, we round up (correctly) to
- * Float.POSITIVE_INFINITY.
- */
- bits |= signum & FloatConsts.SIGN_BIT_MASK;
- return Float.intBitsToFloat(bits);
- }
-
- double doubleValue() {
- if (signum == 0) {
- return 0.0;
- }
- int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1;
- // exponent == floor(log2(abs(this))Double)
- if (exponent < Long.SIZE - 1) {
- return longValue();
- } else if (exponent > Double.MAX_EXPONENT) {
- return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
- }
- /*
- * We need the top SIGNIFICAND_WIDTH bits, including the "implicit"
- * one bit. To make rounding easier, we pick out the top
- * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or
- * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1
- * bits, and signifFloor the top SIGNIFICAND_WIDTH.
- *
- * It helps to consider the real number signif = abs(this) *
- * 2^(SIGNIFICAND_WIDTH - 1 - exponent).
- */
- int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH;
- long twiceSignifFloor;
- // twiceSignifFloor will be == abs().shiftRight(shift).longValue()
- // We do the shift into a long directly to improve performance.
- int nBits = shift & 0x1f;
- int nBits2 = 32 - nBits;
- int highBits;
- int lowBits;
- if (nBits == 0) {
- highBits = mag[0];
- lowBits = mag[1];
- } else {
- highBits = mag[0] >>> nBits;
- lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits);
- if (highBits == 0) {
- highBits = lowBits;
- lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits);
- }
- }
- twiceSignifFloor = ((highBits & LONG_MASK) << 32)
- | (lowBits & LONG_MASK);
- long signifFloor = twiceSignifFloor >> 1;
- signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit
- /*
- * We round up if either the fractional part of signif is strictly
- * greater than 0.5 (which is true if the 0.5 bit is set and any lower
- * bit is set), or if the fractional part of signif is >= 0.5 and
- * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit
- * are set). This is equivalent to the desired HALF_EVEN rounding.
- */
- boolean increment = (twiceSignifFloor & 1) != 0
- && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift);
- long signifRounded = increment ? signifFloor + 1 : signifFloor;
- long bits = (long) ((exponent + DoubleConsts.EXP_BIAS))
- << (DoubleConsts.SIGNIFICAND_WIDTH - 1);
- bits += signifRounded;
- /*
- * If signifRounded == 2^53, we'd need to set all of the significand
- * bits to zero and add 1 to the exponent. This is exactly the behavior
- * we get from just adding signifRounded to bits directly. If the
- * exponent is Double.MAX_EXPONENT, we round up (correctly) to
- * Double.POSITIVE_INFINITY.
- */
- bits |= signum & DoubleConsts.SIGN_BIT_MASK;
- return Double.longBitsToDouble(bits);
- }
-
- static int[] stripLeadingZeroInts(int val[]) {
- int vlen = val.length;
- int keep;
- // Find first nonzero byte
- for (keep = 0; keep < vlen && val[keep] == 0; keep++)
- ;
- return java.util.Arrays.copyOfRange(val, keep, vlen);
- }
-
- static int[] trustedStripLeadingZeroInts(int val[]) {
- int vlen = val.length;
- int keep;
- // Find first nonzero byte
- for (keep = 0; keep < vlen && val[keep] == 0; keep++)
- ;
- return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen);
- }
-
- static int[] stripLeadingZeroBytes(byte a[]) {
- int byteLength = a.length;
- int keep;
- // Find first nonzero byte
- for (keep = 0; keep < byteLength && a[keep] == 0; keep++)
- ;
- // Allocate new array and copy relevant part of input array
- int intLength = ((byteLength - keep) + 3) >>> 2;
- int[] result = new int[intLength];
- int b = byteLength - 1;
- for (int i = intLength-1; i >= 0; i--) {
- result[i] = a[b--] & 0xff;
- int bytesRemaining = b - keep + 1;
- int bytesToTransfer = Math.min(3, bytesRemaining);
- for (int j=8; j <= (bytesToTransfer << 3); j += 8)
- result[i] |= ((a[b--] & 0xff) << j);
- }
- return result;
- }
-
- static int[] makePositive(byte a[]) {
- int keep, k;
- int byteLength = a.length;
- // Find first non-sign (0xff) byte of input
- for (keep=0; keep < byteLength && a[keep] == -1; keep++)
- ;
- /* Allocate output array. If all non-sign bytes are 0x00, we must
- * allocate space for one extra output byte. */
- for (k=keep; k < byteLength && a[k] == 0; k++)
- ;
- int extraByte = (k == byteLength) ? 1 : 0;
- int intLength = ((byteLength - keep + extraByte) + 3) >>> 2;
- int result[] = new int[intLength];
- /* Copy one's complement of input into output, leaving extra
- * byte (if it exists) == 0x00 */
- int b = byteLength - 1;
- for (int i = intLength-1; i >= 0; i--) {
- result[i] = a[b--] & 0xff;
- int numBytesToTransfer = Math.min(3, b-keep+1);
- if (numBytesToTransfer < 0)
- numBytesToTransfer = 0;
- for (int j=8; j <= 8*numBytesToTransfer; j += 8)
- result[i] |= ((a[b--] & 0xff) << j);
- // Mask indicates which bits must be complemented
- int mask = -1 >>> (8*(3-numBytesToTransfer));
- result[i] = ~result[i] & mask;
- }
- // Add one to one's complement to generate two's complement
- for (int i=result.length-1; i >= 0; i--) {
- result[i] = (int)((result[i] & LONG_MASK) + 1);
- if (result[i] != 0)
- break;
- }
- return result;
- }
-
- static int[] makePositive(int a[]) {
- int keep, j;
- // Find first non-sign (0xffffffff) int of input
- for (keep=0; keep < a.length && a[keep] == -1; keep++)
- ;
- /* Allocate output array. If all non-sign ints are 0x00, we must
- * allocate space for one extra output int. */
- for (j=keep; j < a.length && a[j] == 0; j++)
- ;
- int extraInt = (j == a.length ? 1 : 0);
- int result[] = new int[a.length - keep + extraInt];
- /* Copy one's complement of input into output, leaving extra
- * int (if it exists) == 0x00 */
- for (int i = keep; i < a.length; i++)
- result[i - keep + extraInt] = ~a[i];
- // Add one to one's complement to generate two's complement
- for (int i=result.length-1; ++result[i] == 0; i--)
- ;
- return result;
- }
- /*
- * The following two arrays are used for fast String conversions. Both
- * are indexed by radix. The first is the number of digits of the given
- * radix that can fit in a Java long without "going negative", i.e., the
- * highest integer n such that radix**n < 2**63. The second is the
- * "long radix" that tears each number into "long digits", each of which
- * consists of the number of digits in the corresponding element in
- * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have
- * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not
- * used.
- */
- static int digitsPerLong[] = {0, 0,
- 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14,
- 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12};
- static BigInteger longRadix[] = {null, null,
- valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL),
- valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL),
- valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L),
- valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L),
- valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L),
- valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL),
- valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L),
- valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L),
- valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L),
- valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L),
- valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L),
- valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L),
- valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL),
- valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L),
- valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L),
- valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L),
- valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L),
- valueOf(0x41c21cb8e1000000L)};
- /*
- * These two arrays are the integer analogue of above.
- */
- static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11,
- 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
- 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5};
- static int intRadix[] = {0, 0,
- 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800,
- 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61,
- 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000,
- 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d,
- 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40,
- 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41,
- 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400
- };
-
-
- int intLength() {
- return (bitLength() >>> 5) + 1;
- }
- /* Returns sign bit */
- int signBit() {
- return signum < 0 ? 1 : 0;
- }
- /* Returns an int of sign bits */
- int signInt() {
- return signum < 0 ? -1 : 0;
- }
-
- int getInt(int n) {
- if (n < 0)
- return 0;
- if (n >= mag.length)
- return signInt();
- int magInt = mag[mag.length-n-1];
- return (signum >= 0 ? magInt :
- (n <= firstNonzeroIntNum() ? -magInt : ~magInt));
- }
-
- int firstNonzeroIntNum() {
- int fn = firstNonzeroIntNum - 2;
- if (fn == -2) { // firstNonzeroIntNum not initialized yet
- fn = 0;
- // Search for the first nonzero int
- int i;
- int mlen = mag.length;
- for (i = mlen - 1; i >= 0 && mag[i] == 0; i--)
- ;
- fn = mlen - i - 1;
- firstNonzeroIntNum = fn + 2; // offset by two to initialize
- }
- return fn;
- }
-
- static const long serialVersionUID = -8287574255936472291L;
-
- static const ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("signum", Integer.TYPE),
- new ObjectStreamField("magnitude", byte[].class),
- new ObjectStreamField("bitCount", Integer.TYPE),
- new ObjectStreamField("bitLength", Integer.TYPE),
- new ObjectStreamField("firstNonzeroByteNum", Integer.TYPE),
- new ObjectStreamField("lowestSetBit", Integer.TYPE)
- };
-
- void readObject(java.io.ObjectInputStream s)
- throws java.io.IOException, ClassNotFoundException {
- /*
- * In order to maintain compatibility with previous serialized forms,
- * the magnitude of a BigInteger is serialized as an array of bytes.
- * The magnitude field is used as a temporary store for the byte array
- * that is deserialized. The cached computation fields should be
- * transient but are serialized for compatibility reasons.
- */
- // prepare to read the alternate persistent fields
- ObjectInputStream.GetField fields = s.readFields();
- // Read the alternate persistent fields that we care about
- int sign = fields.get("signum", -2);
- byte[] magnitude = (byte[])fields.get("magnitude", null);
- // Validate signum
- if (sign < -1 || sign > 1) {
- String message = "BigInteger: Invalid signum value";
- if (fields.defaulted("signum"))
- message = "BigInteger: Signum not present in stream";
- throw new java.io.StreamCorruptedException(message);
- }
- int[] mag = stripLeadingZeroBytes(magnitude);
- if ((mag.length == 0) != (sign == 0)) {
- String message = "BigInteger: signum-magnitude mismatch";
- if (fields.defaulted("magnitude"))
- message = "BigInteger: Magnitude not present in stream";
- throw new java.io.StreamCorruptedException(message);
- }
- // Commit const fields via Unsafe
- UnsafeHolder.putSign(this, sign);
- // Calculate mag field from magnitude and discard magnitude
- UnsafeHolder.putMag(this, mag);
- if (mag.length >= MAX_MAG_LENGTH) {
- try {
- checkRange();
- } catch (ArithmeticException e) {
- throw new java.io.StreamCorruptedException("BigInteger: Out of the supported range");
- }
- }
- }
- // Support for resetting const fields while deserializing
- static class UnsafeHolder {
- static const sun.misc.Unsafe unsafe;
- static const long signumOffset;
- static const long magOffset;
- static {
- try {
- unsafe = sun.misc.Unsafe.getUnsafe();
- signumOffset = unsafe.objectFieldOffset
- (BigInteger.class.getDeclaredField("signum"));
- magOffset = unsafe.objectFieldOffset
- (BigInteger.class.getDeclaredField("mag"));
- } catch (Exception ex) {
- throw new ExceptionInInitializerError(ex);
- }
- }
- static void putSign(BigInteger bi, int sign) {
- unsafe.putIntVolatile(bi, signumOffset, sign);
- }
- static void putMag(BigInteger bi, int[] magnitude) {
- unsafe.putObjectVolatile(bi, magOffset, magnitude);
- }
- }
-
- void writeObject(ObjectOutputStream s) throws IOException {
- // set the values of the Serializable fields
- ObjectOutputStream.PutField fields = s.putFields();
- fields.put("signum", signum);
- fields.put("magnitude", magSerializedForm());
- // The values written for cached fields are compatible with older
- // versions, but are ignored in readObject so don't otherwise matter.
- fields.put("bitCount", -1);
- fields.put("bitLength", -1);
- fields.put("lowestSetBit", -2);
- fields.put("firstNonzeroByteNum", -2);
- // save them
- s.writeFields();
- }
-
- byte[] magSerializedForm() {
- int len = mag.length;
- int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0]));
- int byteLen = (bitLen + 7) >>> 3;
- byte[] result = new byte[byteLen];
- for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0;
- i >= 0; i--) {
- if (bytesCopied == 4) {
- nextInt = mag[intIndex--];
- bytesCopied = 1;
- } else {
- nextInt >>>= 8;
- bytesCopied++;
- }
- result[i] = (byte)nextInt;
- }
- return result;
- }
-
- long longValueExact() {
- if (mag.length <= 2 && bitLength() <= 63)
- return longValue();
- else
- throw new ArithmeticException("BigInteger out of long range");
- }
-
- int intValueExact() {
- if (mag.length <= 1 && bitLength() <= 31)
- return intValue();
- else
- throw new ArithmeticException("BigInteger out of int range");
- }
-
- short shortValueExact() {
- if (mag.length <= 1 && bitLength() <= 31) {
- int value = intValue();
- if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE)
- return shortValue();
- }
- throw new ArithmeticException("BigInteger out of short range");
- }
-
- byte byteValueExact() {
- if (mag.length <= 1 && bitLength() <= 31) {
- int value = intValue();
- if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE)
- return byteValue();
- }
- throw new ArithmeticException("BigInteger out of byte range");
- }
- static void main(String[] args) {
- BigInteger a = new BigInteger(6);
- a = a.pow(100);
- System.out.println(a);
- }
- }
|