BigInteger.java 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679
  1. /* java.math.BigInteger -- Arbitary precision integers
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2005, 2006, 2007, 2010
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.math;
  33. import gnu.classpath.Configuration;
  34. import gnu.java.lang.CPStringBuilder;
  35. import gnu.java.math.GMP;
  36. import gnu.java.math.MPN;
  37. import java.io.IOException;
  38. import java.io.ObjectInputStream;
  39. import java.io.ObjectOutputStream;
  40. import java.util.Random;
  41. import java.util.logging.Logger;
  42. /**
  43. * Written using on-line Java Platform 1.2 API Specification, as well
  44. * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998) and
  45. * "Applied Cryptography, Second Edition" by Bruce Schneier (Wiley, 1996).
  46. *
  47. * Based primarily on IntNum.java BitOps.java by Per Bothner (per@bothner.com)
  48. * (found in Kawa 1.6.62).
  49. *
  50. * @author Warren Levy (warrenl@cygnus.com)
  51. * @date December 20, 1999.
  52. * @status believed complete and correct.
  53. */
  54. public class BigInteger extends Number implements Comparable<BigInteger>
  55. {
  56. private static final Logger log = Configuration.DEBUG ?
  57. Logger.getLogger(BigInteger.class.getName()) : null;
  58. /** All integers are stored in 2's-complement form.
  59. * If words == null, the ival is the value of this BigInteger.
  60. * Otherwise, the first ival elements of words make the value
  61. * of this BigInteger, stored in little-endian order, 2's-complement form. */
  62. private transient int ival;
  63. private transient int[] words;
  64. // Serialization fields.
  65. // the first three, although not used in the code, are present for
  66. // compatibility with older RI versions of this class. DO NOT REMOVE.
  67. private int bitCount = -1;
  68. private int bitLength = -1;
  69. private int lowestSetBit = -2;
  70. private byte[] magnitude;
  71. private int signum;
  72. private static final long serialVersionUID = -8287574255936472291L;
  73. /** We pre-allocate integers in the range minFixNum..maxFixNum.
  74. * Note that we must at least preallocate 0, 1, and 10. */
  75. private static final int minFixNum = -100;
  76. private static final int maxFixNum = 1024;
  77. private static final int numFixNum = maxFixNum-minFixNum+1;
  78. private static final BigInteger[] smallFixNums;
  79. /** The alter-ego GMP instance for this. */
  80. private transient GMP mpz;
  81. private static final boolean USING_NATIVE = Configuration.WANT_NATIVE_BIG_INTEGER
  82. && initializeLibrary();
  83. static
  84. {
  85. if (USING_NATIVE)
  86. {
  87. smallFixNums = null;
  88. ZERO = valueOf(0L);
  89. ONE = valueOf(1L);
  90. TEN = valueOf(10L);
  91. }
  92. else
  93. {
  94. smallFixNums = new BigInteger[numFixNum];
  95. for (int i = numFixNum; --i >= 0; )
  96. smallFixNums[i] = new BigInteger(i + minFixNum);
  97. ZERO = smallFixNums[-minFixNum];
  98. ONE = smallFixNums[1 - minFixNum];
  99. TEN = smallFixNums[10 - minFixNum];
  100. }
  101. }
  102. /**
  103. * The constant zero as a BigInteger.
  104. * @since 1.2
  105. */
  106. public static final BigInteger ZERO;
  107. /**
  108. * The constant one as a BigInteger.
  109. * @since 1.2
  110. */
  111. public static final BigInteger ONE;
  112. /**
  113. * The constant ten as a BigInteger.
  114. * @since 1.5
  115. */
  116. public static final BigInteger TEN;
  117. /* Rounding modes: */
  118. private static final int FLOOR = 1;
  119. private static final int CEILING = 2;
  120. private static final int TRUNCATE = 3;
  121. private static final int ROUND = 4;
  122. /** When checking the probability of primes, it is most efficient to
  123. * first check the factoring of small primes, so we'll use this array.
  124. */
  125. private static final int[] primes =
  126. { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
  127. 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
  128. 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
  129. 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 };
  130. /** HAC (Handbook of Applied Cryptography), Alfred Menezes & al. Table 4.4. */
  131. private static final int[] k =
  132. {100,150,200,250,300,350,400,500,600,800,1250, Integer.MAX_VALUE};
  133. private static final int[] t =
  134. { 27, 18, 15, 12, 9, 8, 7, 6, 5, 4, 3, 2};
  135. private BigInteger()
  136. {
  137. super();
  138. if (USING_NATIVE)
  139. mpz = new GMP();
  140. }
  141. /* Create a new (non-shared) BigInteger, and initialize to an int. */
  142. private BigInteger(int value)
  143. {
  144. super();
  145. ival = value;
  146. }
  147. public BigInteger(String s, int radix)
  148. {
  149. this();
  150. int len = s.length();
  151. int i, digit;
  152. boolean negative;
  153. byte[] bytes;
  154. char ch = s.charAt(0);
  155. if (ch == '-')
  156. {
  157. negative = true;
  158. i = 1;
  159. bytes = new byte[len - 1];
  160. }
  161. else
  162. {
  163. negative = false;
  164. i = 0;
  165. bytes = new byte[len];
  166. }
  167. int byte_len = 0;
  168. for ( ; i < len; i++)
  169. {
  170. ch = s.charAt(i);
  171. digit = Character.digit(ch, radix);
  172. if (digit < 0)
  173. throw new NumberFormatException("Invalid character at position #" + i);
  174. bytes[byte_len++] = (byte) digit;
  175. }
  176. if (USING_NATIVE)
  177. {
  178. bytes = null;
  179. if (mpz.fromString(s, radix) != 0)
  180. throw new NumberFormatException("String \"" + s
  181. + "\" is NOT a valid number in base "
  182. + radix);
  183. }
  184. else
  185. {
  186. BigInteger result;
  187. // Testing (len < MPN.chars_per_word(radix)) would be more accurate,
  188. // but slightly more expensive, for little practical gain.
  189. if (len <= 15 && radix <= 16)
  190. result = valueOf(Long.parseLong(s, radix));
  191. else
  192. result = valueOf(bytes, byte_len, negative, radix);
  193. this.ival = result.ival;
  194. this.words = result.words;
  195. }
  196. }
  197. public BigInteger(String val)
  198. {
  199. this(val, 10);
  200. }
  201. /* Create a new (non-shared) BigInteger, and initialize from a byte array. */
  202. public BigInteger(byte[] val)
  203. {
  204. this();
  205. if (val == null || val.length < 1)
  206. throw new NumberFormatException();
  207. if (USING_NATIVE)
  208. mpz.fromByteArray(val);
  209. else
  210. {
  211. words = byteArrayToIntArray(val, val[0] < 0 ? -1 : 0);
  212. BigInteger result = make(words, words.length);
  213. this.ival = result.ival;
  214. this.words = result.words;
  215. }
  216. }
  217. public BigInteger(int signum, byte[] magnitude)
  218. {
  219. this();
  220. if (magnitude == null || signum > 1 || signum < -1)
  221. throw new NumberFormatException();
  222. if (signum == 0)
  223. {
  224. int i;
  225. for (i = magnitude.length - 1; i >= 0 && magnitude[i] == 0; --i)
  226. ;
  227. if (i >= 0)
  228. throw new NumberFormatException();
  229. return;
  230. }
  231. if (USING_NATIVE)
  232. mpz.fromSignedMagnitude(magnitude, signum == -1);
  233. else
  234. {
  235. // Magnitude is always positive, so don't ever pass a sign of -1.
  236. words = byteArrayToIntArray(magnitude, 0);
  237. BigInteger result = make(words, words.length);
  238. this.ival = result.ival;
  239. this.words = result.words;
  240. if (signum < 0)
  241. setNegative();
  242. }
  243. }
  244. public BigInteger(int numBits, Random rnd)
  245. {
  246. this();
  247. if (numBits < 0)
  248. throw new IllegalArgumentException();
  249. init(numBits, rnd);
  250. }
  251. private void init(int numBits, Random rnd)
  252. {
  253. if (USING_NATIVE)
  254. {
  255. int length = (numBits + 7) / 8;
  256. byte[] magnitude = new byte[length];
  257. rnd.nextBytes(magnitude);
  258. int discardedBitCount = numBits % 8;
  259. if (discardedBitCount != 0)
  260. {
  261. discardedBitCount = 8 - discardedBitCount;
  262. magnitude[0] = (byte)((magnitude[0] & 0xFF) >>> discardedBitCount);
  263. }
  264. mpz.fromSignedMagnitude(magnitude, false);
  265. magnitude = null;
  266. return;
  267. }
  268. int highbits = numBits & 31;
  269. // minimum number of bytes to store the above number of bits
  270. int highBitByteCount = (highbits + 7) / 8;
  271. // number of bits to discard from the last byte
  272. int discardedBitCount = highbits % 8;
  273. if (discardedBitCount != 0)
  274. discardedBitCount = 8 - discardedBitCount;
  275. byte[] highBitBytes = new byte[highBitByteCount];
  276. if (highbits > 0)
  277. {
  278. rnd.nextBytes(highBitBytes);
  279. highbits = (highBitBytes[highBitByteCount - 1] & 0xFF) >>> discardedBitCount;
  280. for (int i = highBitByteCount - 2; i >= 0; i--)
  281. highbits = (highbits << 8) | (highBitBytes[i] & 0xFF);
  282. }
  283. int nwords = numBits / 32;
  284. while (highbits == 0 && nwords > 0)
  285. {
  286. highbits = rnd.nextInt();
  287. --nwords;
  288. }
  289. if (nwords == 0 && highbits >= 0)
  290. {
  291. ival = highbits;
  292. }
  293. else
  294. {
  295. ival = highbits < 0 ? nwords + 2 : nwords + 1;
  296. words = new int[ival];
  297. words[nwords] = highbits;
  298. while (--nwords >= 0)
  299. words[nwords] = rnd.nextInt();
  300. }
  301. }
  302. public BigInteger(int bitLength, int certainty, Random rnd)
  303. {
  304. this();
  305. BigInteger result = new BigInteger();
  306. while (true)
  307. {
  308. result.init(bitLength, rnd);
  309. result = result.setBit(bitLength - 1);
  310. if (result.isProbablePrime(certainty))
  311. break;
  312. }
  313. if (USING_NATIVE)
  314. mpz.fromBI(result.mpz);
  315. else
  316. {
  317. this.ival = result.ival;
  318. this.words = result.words;
  319. }
  320. }
  321. /**
  322. * Return a BigInteger that is bitLength bits long with a
  323. * probability < 2^-100 of being composite.
  324. *
  325. * @param bitLength length in bits of resulting number
  326. * @param rnd random number generator to use
  327. * @throws ArithmeticException if bitLength < 2
  328. * @since 1.4
  329. */
  330. public static BigInteger probablePrime(int bitLength, Random rnd)
  331. {
  332. if (bitLength < 2)
  333. throw new ArithmeticException();
  334. return new BigInteger(bitLength, 100, rnd);
  335. }
  336. /** Return a (possibly-shared) BigInteger with a given long value. */
  337. public static BigInteger valueOf(long val)
  338. {
  339. if (USING_NATIVE)
  340. {
  341. BigInteger result = new BigInteger();
  342. result.mpz.fromLong(val);
  343. return result;
  344. }
  345. if (val >= minFixNum && val <= maxFixNum)
  346. return smallFixNums[(int) val - minFixNum];
  347. int i = (int) val;
  348. if ((long) i == val)
  349. return new BigInteger(i);
  350. BigInteger result = alloc(2);
  351. result.ival = 2;
  352. result.words[0] = i;
  353. result.words[1] = (int)(val >> 32);
  354. return result;
  355. }
  356. /**
  357. * @return <code>true</code> if the GMP-based native implementation library
  358. * was successfully loaded. Returns <code>false</code> otherwise.
  359. */
  360. private static boolean initializeLibrary()
  361. {
  362. boolean result;
  363. try
  364. {
  365. System.loadLibrary("javamath");
  366. GMP.natInitializeLibrary();
  367. result = true;
  368. }
  369. catch (Throwable x)
  370. {
  371. result = false;
  372. if (Configuration.DEBUG)
  373. {
  374. log.info("Unable to use native BigInteger: " + x);
  375. log.info("Will use a pure Java implementation instead");
  376. }
  377. }
  378. return result;
  379. }
  380. /** Make a canonicalized BigInteger from an array of words.
  381. * The array may be reused (without copying). */
  382. private static BigInteger make(int[] words, int len)
  383. {
  384. if (words == null)
  385. return valueOf(len);
  386. len = BigInteger.wordsNeeded(words, len);
  387. if (len <= 1)
  388. return len == 0 ? ZERO : valueOf(words[0]);
  389. BigInteger num = new BigInteger();
  390. num.words = words;
  391. num.ival = len;
  392. return num;
  393. }
  394. /** Convert a big-endian byte array to a little-endian array of words. */
  395. private static int[] byteArrayToIntArray(byte[] bytes, int sign)
  396. {
  397. // Determine number of words needed.
  398. int[] words = new int[bytes.length/4 + 1];
  399. int nwords = words.length;
  400. // Create a int out of modulo 4 high order bytes.
  401. int bptr = 0;
  402. int word = sign;
  403. for (int i = bytes.length % 4; i > 0; --i, bptr++)
  404. word = (word << 8) | (bytes[bptr] & 0xff);
  405. words[--nwords] = word;
  406. // Elements remaining in byte[] are a multiple of 4.
  407. while (nwords > 0)
  408. words[--nwords] = bytes[bptr++] << 24 |
  409. (bytes[bptr++] & 0xff) << 16 |
  410. (bytes[bptr++] & 0xff) << 8 |
  411. (bytes[bptr++] & 0xff);
  412. return words;
  413. }
  414. /** Allocate a new non-shared BigInteger.
  415. * @param nwords number of words to allocate
  416. */
  417. private static BigInteger alloc(int nwords)
  418. {
  419. BigInteger result = new BigInteger();
  420. if (nwords > 1)
  421. result.words = new int[nwords];
  422. return result;
  423. }
  424. /** Change words.length to nwords.
  425. * We allow words.length to be upto nwords+2 without reallocating.
  426. */
  427. private void realloc(int nwords)
  428. {
  429. if (nwords == 0)
  430. {
  431. if (words != null)
  432. {
  433. if (ival > 0)
  434. ival = words[0];
  435. words = null;
  436. }
  437. }
  438. else if (words == null
  439. || words.length < nwords
  440. || words.length > nwords + 2)
  441. {
  442. int[] new_words = new int [nwords];
  443. if (words == null)
  444. {
  445. new_words[0] = ival;
  446. ival = 1;
  447. }
  448. else
  449. {
  450. if (nwords < ival)
  451. ival = nwords;
  452. System.arraycopy(words, 0, new_words, 0, ival);
  453. }
  454. words = new_words;
  455. }
  456. }
  457. private boolean isNegative()
  458. {
  459. return (words == null ? ival : words[ival - 1]) < 0;
  460. }
  461. public int signum()
  462. {
  463. if (USING_NATIVE)
  464. return mpz.compare(ZERO.mpz);
  465. if (ival == 0 && words == null)
  466. return 0;
  467. int top = words == null ? ival : words[ival-1];
  468. return top < 0 ? -1 : 1;
  469. }
  470. private static int compareTo(BigInteger x, BigInteger y)
  471. {
  472. if (USING_NATIVE)
  473. {
  474. int dummy = y.signum; // force NPE check
  475. return x.mpz.compare(y.mpz);
  476. }
  477. if (x.words == null && y.words == null)
  478. return x.ival < y.ival ? -1 : x.ival > y.ival ? 1 : 0;
  479. boolean x_negative = x.isNegative();
  480. boolean y_negative = y.isNegative();
  481. if (x_negative != y_negative)
  482. return x_negative ? -1 : 1;
  483. int x_len = x.words == null ? 1 : x.ival;
  484. int y_len = y.words == null ? 1 : y.ival;
  485. if (x_len != y_len)
  486. return (x_len > y_len) != x_negative ? 1 : -1;
  487. return MPN.cmp(x.words, y.words, x_len);
  488. }
  489. /** @since 1.2 */
  490. public int compareTo(BigInteger val)
  491. {
  492. return compareTo(this, val);
  493. }
  494. public BigInteger min(BigInteger val)
  495. {
  496. return compareTo(this, val) < 0 ? this : val;
  497. }
  498. public BigInteger max(BigInteger val)
  499. {
  500. return compareTo(this, val) > 0 ? this : val;
  501. }
  502. private boolean isZero()
  503. {
  504. return words == null && ival == 0;
  505. }
  506. private boolean isOne()
  507. {
  508. return words == null && ival == 1;
  509. }
  510. /** Calculate how many words are significant in words[0:len-1].
  511. * Returns the least value x such that x>0 && words[0:x-1]==words[0:len-1],
  512. * when words is viewed as a 2's complement integer.
  513. */
  514. private static int wordsNeeded(int[] words, int len)
  515. {
  516. int i = len;
  517. if (i > 0)
  518. {
  519. int word = words[--i];
  520. if (word == -1)
  521. {
  522. while (i > 0 && (word = words[i - 1]) < 0)
  523. {
  524. i--;
  525. if (word != -1) break;
  526. }
  527. }
  528. else
  529. {
  530. while (word == 0 && i > 0 && (word = words[i - 1]) >= 0) i--;
  531. }
  532. }
  533. return i + 1;
  534. }
  535. private BigInteger canonicalize()
  536. {
  537. if (words != null
  538. && (ival = BigInteger.wordsNeeded(words, ival)) <= 1)
  539. {
  540. if (ival == 1)
  541. ival = words[0];
  542. words = null;
  543. }
  544. if (words == null && ival >= minFixNum && ival <= maxFixNum)
  545. return smallFixNums[ival - minFixNum];
  546. return this;
  547. }
  548. /** Add two ints, yielding a BigInteger. */
  549. private static BigInteger add(int x, int y)
  550. {
  551. return valueOf((long) x + (long) y);
  552. }
  553. /** Add a BigInteger and an int, yielding a new BigInteger. */
  554. private static BigInteger add(BigInteger x, int y)
  555. {
  556. if (x.words == null)
  557. return BigInteger.add(x.ival, y);
  558. BigInteger result = new BigInteger(0);
  559. result.setAdd(x, y);
  560. return result.canonicalize();
  561. }
  562. /** Set this to the sum of x and y.
  563. * OK if x==this. */
  564. private void setAdd(BigInteger x, int y)
  565. {
  566. if (x.words == null)
  567. {
  568. set((long) x.ival + (long) y);
  569. return;
  570. }
  571. int len = x.ival;
  572. realloc(len + 1);
  573. long carry = y;
  574. for (int i = 0; i < len; i++)
  575. {
  576. carry += ((long) x.words[i] & 0xffffffffL);
  577. words[i] = (int) carry;
  578. carry >>= 32;
  579. }
  580. if (x.words[len - 1] < 0)
  581. carry--;
  582. words[len] = (int) carry;
  583. ival = wordsNeeded(words, len + 1);
  584. }
  585. /** Destructively add an int to this. */
  586. private void setAdd(int y)
  587. {
  588. setAdd(this, y);
  589. }
  590. /** Destructively set the value of this to a long. */
  591. private void set(long y)
  592. {
  593. int i = (int) y;
  594. if ((long) i == y)
  595. {
  596. ival = i;
  597. words = null;
  598. }
  599. else
  600. {
  601. realloc(2);
  602. words[0] = i;
  603. words[1] = (int) (y >> 32);
  604. ival = 2;
  605. }
  606. }
  607. /** Destructively set the value of this to the given words.
  608. * The words array is reused, not copied. */
  609. private void set(int[] words, int length)
  610. {
  611. this.ival = length;
  612. this.words = words;
  613. }
  614. /** Destructively set the value of this to that of y. */
  615. private void set(BigInteger y)
  616. {
  617. if (y.words == null)
  618. set(y.ival);
  619. else if (this != y)
  620. {
  621. realloc(y.ival);
  622. System.arraycopy(y.words, 0, words, 0, y.ival);
  623. ival = y.ival;
  624. }
  625. }
  626. /** Add two BigIntegers, yielding their sum as another BigInteger. */
  627. private static BigInteger add(BigInteger x, BigInteger y, int k)
  628. {
  629. if (x.words == null && y.words == null)
  630. return valueOf((long) k * (long) y.ival + (long) x.ival);
  631. if (k != 1)
  632. {
  633. if (k == -1)
  634. y = BigInteger.neg(y);
  635. else
  636. y = BigInteger.times(y, valueOf(k));
  637. }
  638. if (x.words == null)
  639. return BigInteger.add(y, x.ival);
  640. if (y.words == null)
  641. return BigInteger.add(x, y.ival);
  642. // Both are big
  643. if (y.ival > x.ival)
  644. { // Swap so x is longer then y.
  645. BigInteger tmp = x; x = y; y = tmp;
  646. }
  647. BigInteger result = alloc(x.ival + 1);
  648. int i = y.ival;
  649. long carry = MPN.add_n(result.words, x.words, y.words, i);
  650. long y_ext = y.words[i - 1] < 0 ? 0xffffffffL : 0;
  651. for (; i < x.ival; i++)
  652. {
  653. carry += ((long) x.words[i] & 0xffffffffL) + y_ext;
  654. result.words[i] = (int) carry;
  655. carry >>>= 32;
  656. }
  657. if (x.words[i - 1] < 0)
  658. y_ext--;
  659. result.words[i] = (int) (carry + y_ext);
  660. result.ival = i+1;
  661. return result.canonicalize();
  662. }
  663. public BigInteger add(BigInteger val)
  664. {
  665. if (USING_NATIVE)
  666. {
  667. int dummy = val.signum; // force NPE check
  668. BigInteger result = new BigInteger();
  669. mpz.add(val.mpz, result.mpz);
  670. return result;
  671. }
  672. return add(this, val, 1);
  673. }
  674. public BigInteger subtract(BigInteger val)
  675. {
  676. if (USING_NATIVE)
  677. {
  678. int dummy = val.signum; // force NPE check
  679. BigInteger result = new BigInteger();
  680. mpz.subtract(val.mpz, result.mpz);
  681. return result;
  682. }
  683. return add(this, val, -1);
  684. }
  685. private static BigInteger times(BigInteger x, int y)
  686. {
  687. if (y == 0)
  688. return ZERO;
  689. if (y == 1)
  690. return x;
  691. int[] xwords = x.words;
  692. int xlen = x.ival;
  693. if (xwords == null)
  694. return valueOf((long) xlen * (long) y);
  695. boolean negative;
  696. BigInteger result = BigInteger.alloc(xlen + 1);
  697. if (xwords[xlen - 1] < 0)
  698. {
  699. negative = true;
  700. negate(result.words, xwords, xlen);
  701. xwords = result.words;
  702. }
  703. else
  704. negative = false;
  705. if (y < 0)
  706. {
  707. negative = !negative;
  708. y = -y;
  709. }
  710. result.words[xlen] = MPN.mul_1(result.words, xwords, xlen, y);
  711. result.ival = xlen + 1;
  712. if (negative)
  713. result.setNegative();
  714. return result.canonicalize();
  715. }
  716. private static BigInteger times(BigInteger x, BigInteger y)
  717. {
  718. if (y.words == null)
  719. return times(x, y.ival);
  720. if (x.words == null)
  721. return times(y, x.ival);
  722. boolean negative = false;
  723. int[] xwords;
  724. int[] ywords;
  725. int xlen = x.ival;
  726. int ylen = y.ival;
  727. if (x.isNegative())
  728. {
  729. negative = true;
  730. xwords = new int[xlen];
  731. negate(xwords, x.words, xlen);
  732. }
  733. else
  734. {
  735. negative = false;
  736. xwords = x.words;
  737. }
  738. if (y.isNegative())
  739. {
  740. negative = !negative;
  741. ywords = new int[ylen];
  742. negate(ywords, y.words, ylen);
  743. }
  744. else
  745. ywords = y.words;
  746. // Swap if x is shorter then y.
  747. if (xlen < ylen)
  748. {
  749. int[] twords = xwords; xwords = ywords; ywords = twords;
  750. int tlen = xlen; xlen = ylen; ylen = tlen;
  751. }
  752. BigInteger result = BigInteger.alloc(xlen+ylen);
  753. MPN.mul(result.words, xwords, xlen, ywords, ylen);
  754. result.ival = xlen+ylen;
  755. if (negative)
  756. result.setNegative();
  757. return result.canonicalize();
  758. }
  759. public BigInteger multiply(BigInteger y)
  760. {
  761. if (USING_NATIVE)
  762. {
  763. int dummy = y.signum; // force NPE check
  764. BigInteger result = new BigInteger();
  765. mpz.multiply(y.mpz, result.mpz);
  766. return result;
  767. }
  768. return times(this, y);
  769. }
  770. private static void divide(long x, long y,
  771. BigInteger quotient, BigInteger remainder,
  772. int rounding_mode)
  773. {
  774. boolean xNegative, yNegative;
  775. if (x < 0)
  776. {
  777. xNegative = true;
  778. if (x == Long.MIN_VALUE)
  779. {
  780. divide(valueOf(x), valueOf(y),
  781. quotient, remainder, rounding_mode);
  782. return;
  783. }
  784. x = -x;
  785. }
  786. else
  787. xNegative = false;
  788. if (y < 0)
  789. {
  790. yNegative = true;
  791. if (y == Long.MIN_VALUE)
  792. {
  793. if (rounding_mode == TRUNCATE)
  794. { // x != Long.Min_VALUE implies abs(x) < abs(y)
  795. if (quotient != null)
  796. quotient.set(0);
  797. if (remainder != null)
  798. remainder.set(x);
  799. }
  800. else
  801. divide(valueOf(x), valueOf(y),
  802. quotient, remainder, rounding_mode);
  803. return;
  804. }
  805. y = -y;
  806. }
  807. else
  808. yNegative = false;
  809. long q = x / y;
  810. long r = x % y;
  811. boolean qNegative = xNegative ^ yNegative;
  812. boolean add_one = false;
  813. if (r != 0)
  814. {
  815. switch (rounding_mode)
  816. {
  817. case TRUNCATE:
  818. break;
  819. case CEILING:
  820. case FLOOR:
  821. if (qNegative == (rounding_mode == FLOOR))
  822. add_one = true;
  823. break;
  824. case ROUND:
  825. add_one = r > ((y - (q & 1)) >> 1);
  826. break;
  827. }
  828. }
  829. if (quotient != null)
  830. {
  831. if (add_one)
  832. q++;
  833. if (qNegative)
  834. q = -q;
  835. quotient.set(q);
  836. }
  837. if (remainder != null)
  838. {
  839. // The remainder is by definition: X-Q*Y
  840. if (add_one)
  841. {
  842. // Subtract the remainder from Y.
  843. r = y - r;
  844. // In this case, abs(Q*Y) > abs(X).
  845. // So sign(remainder) = -sign(X).
  846. xNegative = ! xNegative;
  847. }
  848. else
  849. {
  850. // If !add_one, then: abs(Q*Y) <= abs(X).
  851. // So sign(remainder) = sign(X).
  852. }
  853. if (xNegative)
  854. r = -r;
  855. remainder.set(r);
  856. }
  857. }
  858. /** Divide two integers, yielding quotient and remainder.
  859. * @param x the numerator in the division
  860. * @param y the denominator in the division
  861. * @param quotient is set to the quotient of the result (iff quotient!=null)
  862. * @param remainder is set to the remainder of the result
  863. * (iff remainder!=null)
  864. * @param rounding_mode one of FLOOR, CEILING, TRUNCATE, or ROUND.
  865. */
  866. private static void divide(BigInteger x, BigInteger y,
  867. BigInteger quotient, BigInteger remainder,
  868. int rounding_mode)
  869. {
  870. if ((x.words == null || x.ival <= 2)
  871. && (y.words == null || y.ival <= 2))
  872. {
  873. long x_l = x.longValue();
  874. long y_l = y.longValue();
  875. if (x_l != Long.MIN_VALUE && y_l != Long.MIN_VALUE)
  876. {
  877. divide(x_l, y_l, quotient, remainder, rounding_mode);
  878. return;
  879. }
  880. }
  881. boolean xNegative = x.isNegative();
  882. boolean yNegative = y.isNegative();
  883. boolean qNegative = xNegative ^ yNegative;
  884. int ylen = y.words == null ? 1 : y.ival;
  885. int[] ywords = new int[ylen];
  886. y.getAbsolute(ywords);
  887. while (ylen > 1 && ywords[ylen - 1] == 0) ylen--;
  888. int xlen = x.words == null ? 1 : x.ival;
  889. int[] xwords = new int[xlen+2];
  890. x.getAbsolute(xwords);
  891. while (xlen > 1 && xwords[xlen-1] == 0) xlen--;
  892. int qlen, rlen;
  893. int cmpval = MPN.cmp(xwords, xlen, ywords, ylen);
  894. if (cmpval < 0) // abs(x) < abs(y)
  895. { // quotient = 0; remainder = num.
  896. int[] rwords = xwords; xwords = ywords; ywords = rwords;
  897. rlen = xlen; qlen = 1; xwords[0] = 0;
  898. }
  899. else if (cmpval == 0) // abs(x) == abs(y)
  900. {
  901. xwords[0] = 1; qlen = 1; // quotient = 1
  902. ywords[0] = 0; rlen = 1; // remainder = 0;
  903. }
  904. else if (ylen == 1)
  905. {
  906. qlen = xlen;
  907. // Need to leave room for a word of leading zeros if dividing by 1
  908. // and the dividend has the high bit set. It might be safe to
  909. // increment qlen in all cases, but it certainly is only necessary
  910. // in the following case.
  911. if (ywords[0] == 1 && xwords[xlen-1] < 0)
  912. qlen++;
  913. rlen = 1;
  914. ywords[0] = MPN.divmod_1(xwords, xwords, xlen, ywords[0]);
  915. }
  916. else // abs(x) > abs(y)
  917. {
  918. // Normalize the denominator, i.e. make its most significant bit set by
  919. // shifting it normalization_steps bits to the left. Also shift the
  920. // numerator the same number of steps (to keep the quotient the same!).
  921. int nshift = MPN.count_leading_zeros(ywords[ylen - 1]);
  922. if (nshift != 0)
  923. {
  924. // Shift up the denominator setting the most significant bit of
  925. // the most significant word.
  926. MPN.lshift(ywords, 0, ywords, ylen, nshift);
  927. // Shift up the numerator, possibly introducing a new most
  928. // significant word.
  929. int x_high = MPN.lshift(xwords, 0, xwords, xlen, nshift);
  930. xwords[xlen++] = x_high;
  931. }
  932. if (xlen == ylen)
  933. xwords[xlen++] = 0;
  934. MPN.divide(xwords, xlen, ywords, ylen);
  935. rlen = ylen;
  936. MPN.rshift0 (ywords, xwords, 0, rlen, nshift);
  937. qlen = xlen + 1 - ylen;
  938. if (quotient != null)
  939. {
  940. for (int i = 0; i < qlen; i++)
  941. xwords[i] = xwords[i+ylen];
  942. }
  943. }
  944. if (ywords[rlen-1] < 0)
  945. {
  946. ywords[rlen] = 0;
  947. rlen++;
  948. }
  949. // Now the quotient is in xwords, and the remainder is in ywords.
  950. boolean add_one = false;
  951. if (rlen > 1 || ywords[0] != 0)
  952. { // Non-zero remainder i.e. in-exact quotient.
  953. switch (rounding_mode)
  954. {
  955. case TRUNCATE:
  956. break;
  957. case CEILING:
  958. case FLOOR:
  959. if (qNegative == (rounding_mode == FLOOR))
  960. add_one = true;
  961. break;
  962. case ROUND:
  963. // int cmp = compareTo(remainder<<1, abs(y));
  964. BigInteger tmp = remainder == null ? new BigInteger() : remainder;
  965. tmp.set(ywords, rlen);
  966. tmp = shift(tmp, 1);
  967. if (yNegative)
  968. tmp.setNegative();
  969. int cmp = compareTo(tmp, y);
  970. // Now cmp == compareTo(sign(y)*(remainder<<1), y)
  971. if (yNegative)
  972. cmp = -cmp;
  973. add_one = (cmp == 1) || (cmp == 0 && (xwords[0]&1) != 0);
  974. }
  975. }
  976. if (quotient != null)
  977. {
  978. quotient.set(xwords, qlen);
  979. if (qNegative)
  980. {
  981. if (add_one) // -(quotient + 1) == ~(quotient)
  982. quotient.setInvert();
  983. else
  984. quotient.setNegative();
  985. }
  986. else if (add_one)
  987. quotient.setAdd(1);
  988. }
  989. if (remainder != null)
  990. {
  991. // The remainder is by definition: X-Q*Y
  992. remainder.set(ywords, rlen);
  993. if (add_one)
  994. {
  995. // Subtract the remainder from Y:
  996. // abs(R) = abs(Y) - abs(orig_rem) = -(abs(orig_rem) - abs(Y)).
  997. BigInteger tmp;
  998. if (y.words == null)
  999. {
  1000. tmp = remainder;
  1001. tmp.set(yNegative ? ywords[0] + y.ival : ywords[0] - y.ival);
  1002. }
  1003. else
  1004. tmp = BigInteger.add(remainder, y, yNegative ? 1 : -1);
  1005. // Now tmp <= 0.
  1006. // In this case, abs(Q) = 1 + floor(abs(X)/abs(Y)).
  1007. // Hence, abs(Q*Y) > abs(X).
  1008. // So sign(remainder) = -sign(X).
  1009. if (xNegative)
  1010. remainder.setNegative(tmp);
  1011. else
  1012. remainder.set(tmp);
  1013. }
  1014. else
  1015. {
  1016. // If !add_one, then: abs(Q*Y) <= abs(X).
  1017. // So sign(remainder) = sign(X).
  1018. if (xNegative)
  1019. remainder.setNegative();
  1020. }
  1021. }
  1022. }
  1023. public BigInteger divide(BigInteger val)
  1024. {
  1025. if (USING_NATIVE)
  1026. {
  1027. if (val.compareTo(ZERO) == 0)
  1028. throw new ArithmeticException("divisor is zero");
  1029. BigInteger result = new BigInteger();
  1030. mpz.quotient(val.mpz, result.mpz);
  1031. return result;
  1032. }
  1033. if (val.isZero())
  1034. throw new ArithmeticException("divisor is zero");
  1035. BigInteger quot = new BigInteger();
  1036. divide(this, val, quot, null, TRUNCATE);
  1037. return quot.canonicalize();
  1038. }
  1039. public BigInteger remainder(BigInteger val)
  1040. {
  1041. if (USING_NATIVE)
  1042. {
  1043. if (val.compareTo(ZERO) == 0)
  1044. throw new ArithmeticException("divisor is zero");
  1045. BigInteger result = new BigInteger();
  1046. mpz.remainder(val.mpz, result.mpz);
  1047. return result;
  1048. }
  1049. if (val.isZero())
  1050. throw new ArithmeticException("divisor is zero");
  1051. BigInteger rem = new BigInteger();
  1052. divide(this, val, null, rem, TRUNCATE);
  1053. return rem.canonicalize();
  1054. }
  1055. public BigInteger[] divideAndRemainder(BigInteger val)
  1056. {
  1057. if (USING_NATIVE)
  1058. {
  1059. if (val.compareTo(ZERO) == 0)
  1060. throw new ArithmeticException("divisor is zero");
  1061. BigInteger q = new BigInteger();
  1062. BigInteger r = new BigInteger();
  1063. mpz.quotientAndRemainder(val.mpz, q.mpz, r.mpz);
  1064. return new BigInteger[] { q, r };
  1065. }
  1066. if (val.isZero())
  1067. throw new ArithmeticException("divisor is zero");
  1068. BigInteger[] result = new BigInteger[2];
  1069. result[0] = new BigInteger();
  1070. result[1] = new BigInteger();
  1071. divide(this, val, result[0], result[1], TRUNCATE);
  1072. result[0].canonicalize();
  1073. result[1].canonicalize();
  1074. return result;
  1075. }
  1076. public BigInteger mod(BigInteger m)
  1077. {
  1078. if (USING_NATIVE)
  1079. {
  1080. int dummy = m.signum; // force NPE check
  1081. if (m.compareTo(ZERO) < 1)
  1082. throw new ArithmeticException("non-positive modulus");
  1083. BigInteger result = new BigInteger();
  1084. mpz.modulo(m.mpz, result.mpz);
  1085. return result;
  1086. }
  1087. if (m.isNegative() || m.isZero())
  1088. throw new ArithmeticException("non-positive modulus");
  1089. BigInteger rem = new BigInteger();
  1090. divide(this, m, null, rem, FLOOR);
  1091. return rem.canonicalize();
  1092. }
  1093. /** Calculate the integral power of a BigInteger.
  1094. * @param exponent the exponent (must be non-negative)
  1095. */
  1096. public BigInteger pow(int exponent)
  1097. {
  1098. if (exponent <= 0)
  1099. {
  1100. if (exponent == 0)
  1101. return ONE;
  1102. throw new ArithmeticException("negative exponent");
  1103. }
  1104. if (USING_NATIVE)
  1105. {
  1106. BigInteger result = new BigInteger();
  1107. mpz.pow(exponent, result.mpz);
  1108. return result;
  1109. }
  1110. if (isZero())
  1111. return this;
  1112. int plen = words == null ? 1 : ival; // Length of pow2.
  1113. int blen = ((bitLength() * exponent) >> 5) + 2 * plen;
  1114. boolean negative = isNegative() && (exponent & 1) != 0;
  1115. int[] pow2 = new int [blen];
  1116. int[] rwords = new int [blen];
  1117. int[] work = new int [blen];
  1118. getAbsolute(pow2); // pow2 = abs(this);
  1119. int rlen = 1;
  1120. rwords[0] = 1; // rwords = 1;
  1121. for (;;) // for (i = 0; ; i++)
  1122. {
  1123. // pow2 == this**(2**i)
  1124. // prod = this**(sum(j=0..i-1, (exponent>>j)&1))
  1125. if ((exponent & 1) != 0)
  1126. { // r *= pow2
  1127. MPN.mul(work, pow2, plen, rwords, rlen);
  1128. int[] temp = work; work = rwords; rwords = temp;
  1129. rlen += plen;
  1130. while (rwords[rlen - 1] == 0) rlen--;
  1131. }
  1132. exponent >>= 1;
  1133. if (exponent == 0)
  1134. break;
  1135. // pow2 *= pow2;
  1136. MPN.mul(work, pow2, plen, pow2, plen);
  1137. int[] temp = work; work = pow2; pow2 = temp; // swap to avoid a copy
  1138. plen *= 2;
  1139. while (pow2[plen - 1] == 0) plen--;
  1140. }
  1141. if (rwords[rlen - 1] < 0)
  1142. rlen++;
  1143. if (negative)
  1144. negate(rwords, rwords, rlen);
  1145. return BigInteger.make(rwords, rlen);
  1146. }
  1147. private static int[] euclidInv(int a, int b, int prevDiv)
  1148. {
  1149. if (b == 0)
  1150. throw new ArithmeticException("not invertible");
  1151. if (b == 1)
  1152. // Success: values are indeed invertible!
  1153. // Bottom of the recursion reached; start unwinding.
  1154. return new int[] { -prevDiv, 1 };
  1155. int[] xy = euclidInv(b, a % b, a / b); // Recursion happens here.
  1156. a = xy[0]; // use our local copy of 'a' as a work var
  1157. xy[0] = a * -prevDiv + xy[1];
  1158. xy[1] = a;
  1159. return xy;
  1160. }
  1161. private static void euclidInv(BigInteger a, BigInteger b,
  1162. BigInteger prevDiv, BigInteger[] xy)
  1163. {
  1164. if (b.isZero())
  1165. throw new ArithmeticException("not invertible");
  1166. if (b.isOne())
  1167. {
  1168. // Success: values are indeed invertible!
  1169. // Bottom of the recursion reached; start unwinding.
  1170. xy[0] = neg(prevDiv);
  1171. xy[1] = ONE;
  1172. return;
  1173. }
  1174. // Recursion happens in the following conditional!
  1175. // If a just contains an int, then use integer math for the rest.
  1176. if (a.words == null)
  1177. {
  1178. int[] xyInt = euclidInv(b.ival, a.ival % b.ival, a.ival / b.ival);
  1179. xy[0] = new BigInteger(xyInt[0]);
  1180. xy[1] = new BigInteger(xyInt[1]);
  1181. }
  1182. else
  1183. {
  1184. BigInteger rem = new BigInteger();
  1185. BigInteger quot = new BigInteger();
  1186. divide(a, b, quot, rem, FLOOR);
  1187. // quot and rem may not be in canonical form. ensure
  1188. rem.canonicalize();
  1189. quot.canonicalize();
  1190. euclidInv(b, rem, quot, xy);
  1191. }
  1192. BigInteger t = xy[0];
  1193. xy[0] = add(xy[1], times(t, prevDiv), -1);
  1194. xy[1] = t;
  1195. }
  1196. public BigInteger modInverse(BigInteger y)
  1197. {
  1198. if (USING_NATIVE)
  1199. {
  1200. int dummy = y.signum; // force NPE check
  1201. if (mpz.compare(ZERO.mpz) < 1)
  1202. throw new ArithmeticException("non-positive modulo");
  1203. BigInteger result = new BigInteger();
  1204. mpz.modInverse(y.mpz, result.mpz);
  1205. return result;
  1206. }
  1207. if (y.isNegative() || y.isZero())
  1208. throw new ArithmeticException("non-positive modulo");
  1209. // Degenerate cases.
  1210. if (y.isOne())
  1211. return ZERO;
  1212. if (isOne())
  1213. return ONE;
  1214. // Use Euclid's algorithm as in gcd() but do this recursively
  1215. // rather than in a loop so we can use the intermediate results as we
  1216. // unwind from the recursion.
  1217. // Used http://www.math.nmsu.edu/~crypto/EuclideanAlgo.html as reference.
  1218. BigInteger result = new BigInteger();
  1219. boolean swapped = false;
  1220. if (y.words == null)
  1221. {
  1222. // The result is guaranteed to be less than the modulus, y (which is
  1223. // an int), so simplify this by working with the int result of this
  1224. // modulo y. Also, if this is negative, make it positive via modulo
  1225. // math. Note that BigInteger.mod() must be used even if this is
  1226. // already an int as the % operator would provide a negative result if
  1227. // this is negative, BigInteger.mod() never returns negative values.
  1228. int xval = (words != null || isNegative()) ? mod(y).ival : ival;
  1229. int yval = y.ival;
  1230. // Swap values so x > y.
  1231. if (yval > xval)
  1232. {
  1233. int tmp = xval; xval = yval; yval = tmp;
  1234. swapped = true;
  1235. }
  1236. // Normally, the result is in the 2nd element of the array, but
  1237. // if originally x < y, then x and y were swapped and the result
  1238. // is in the 1st element of the array.
  1239. result.ival =
  1240. euclidInv(yval, xval % yval, xval / yval)[swapped ? 0 : 1];
  1241. // Result can't be negative, so make it positive by adding the
  1242. // original modulus, y.ival (not the possibly "swapped" yval).
  1243. if (result.ival < 0)
  1244. result.ival += y.ival;
  1245. }
  1246. else
  1247. {
  1248. // As above, force this to be a positive value via modulo math.
  1249. BigInteger x = isNegative() ? this.mod(y) : this;
  1250. // Swap values so x > y.
  1251. if (x.compareTo(y) < 0)
  1252. {
  1253. result = x; x = y; y = result; // use 'result' as a work var
  1254. swapped = true;
  1255. }
  1256. // As above (for ints), result will be in the 2nd element unless
  1257. // the original x and y were swapped.
  1258. BigInteger rem = new BigInteger();
  1259. BigInteger quot = new BigInteger();
  1260. divide(x, y, quot, rem, FLOOR);
  1261. // quot and rem may not be in canonical form. ensure
  1262. rem.canonicalize();
  1263. quot.canonicalize();
  1264. BigInteger[] xy = new BigInteger[2];
  1265. euclidInv(y, rem, quot, xy);
  1266. result = swapped ? xy[0] : xy[1];
  1267. // Result can't be negative, so make it positive by adding the
  1268. // original modulus, y (which is now x if they were swapped).
  1269. if (result.isNegative())
  1270. result = add(result, swapped ? x : y, 1);
  1271. }
  1272. return result;
  1273. }
  1274. public BigInteger modPow(BigInteger exponent, BigInteger m)
  1275. {
  1276. if (USING_NATIVE)
  1277. {
  1278. int dummy = exponent.signum; // force NPE check
  1279. if (m.mpz.compare(ZERO.mpz) < 1)
  1280. throw new ArithmeticException("non-positive modulo");
  1281. BigInteger result = new BigInteger();
  1282. mpz.modPow(exponent.mpz, m.mpz, result.mpz);
  1283. return result;
  1284. }
  1285. if (m.isNegative() || m.isZero())
  1286. throw new ArithmeticException("non-positive modulo");
  1287. if (exponent.isNegative())
  1288. return modInverse(m).modPow(exponent.negate(), m);
  1289. if (exponent.isOne())
  1290. return mod(m);
  1291. // To do this naively by first raising this to the power of exponent
  1292. // and then performing modulo m would be extremely expensive, especially
  1293. // for very large numbers. The solution is found in Number Theory
  1294. // where a combination of partial powers and moduli can be done easily.
  1295. //
  1296. // We'll use the algorithm for Additive Chaining which can be found on
  1297. // p. 244 of "Applied Cryptography, Second Edition" by Bruce Schneier.
  1298. BigInteger s = ONE;
  1299. BigInteger t = this;
  1300. BigInteger u = exponent;
  1301. while (!u.isZero())
  1302. {
  1303. if (u.and(ONE).isOne())
  1304. s = times(s, t).mod(m);
  1305. u = u.shiftRight(1);
  1306. t = times(t, t).mod(m);
  1307. }
  1308. return s;
  1309. }
  1310. /** Calculate Greatest Common Divisor for non-negative ints. */
  1311. private static int gcd(int a, int b)
  1312. {
  1313. // Euclid's algorithm, copied from libg++.
  1314. int tmp;
  1315. if (b > a)
  1316. {
  1317. tmp = a; a = b; b = tmp;
  1318. }
  1319. for(;;)
  1320. {
  1321. if (b == 0)
  1322. return a;
  1323. if (b == 1)
  1324. return b;
  1325. tmp = b;
  1326. b = a % b;
  1327. a = tmp;
  1328. }
  1329. }
  1330. public BigInteger gcd(BigInteger y)
  1331. {
  1332. if (USING_NATIVE)
  1333. {
  1334. int dummy = y.signum; // force NPE check
  1335. BigInteger result = new BigInteger();
  1336. mpz.gcd(y.mpz, result.mpz);
  1337. return result;
  1338. }
  1339. int xval = ival;
  1340. int yval = y.ival;
  1341. if (words == null)
  1342. {
  1343. if (xval == 0)
  1344. return abs(y);
  1345. if (y.words == null
  1346. && xval != Integer.MIN_VALUE && yval != Integer.MIN_VALUE)
  1347. {
  1348. if (xval < 0)
  1349. xval = -xval;
  1350. if (yval < 0)
  1351. yval = -yval;
  1352. return valueOf(gcd(xval, yval));
  1353. }
  1354. xval = 1;
  1355. }
  1356. if (y.words == null)
  1357. {
  1358. if (yval == 0)
  1359. return abs(this);
  1360. yval = 1;
  1361. }
  1362. int len = (xval > yval ? xval : yval) + 1;
  1363. int[] xwords = new int[len];
  1364. int[] ywords = new int[len];
  1365. getAbsolute(xwords);
  1366. y.getAbsolute(ywords);
  1367. len = MPN.gcd(xwords, ywords, len);
  1368. BigInteger result = new BigInteger(0);
  1369. result.ival = len;
  1370. result.words = xwords;
  1371. return result.canonicalize();
  1372. }
  1373. /**
  1374. * <p>Returns <code>true</code> if this BigInteger is probably prime,
  1375. * <code>false</code> if it's definitely composite. If <code>certainty</code>
  1376. * is <code><= 0</code>, <code>true</code> is returned.</p>
  1377. *
  1378. * @param certainty a measure of the uncertainty that the caller is willing
  1379. * to tolerate: if the call returns <code>true</code> the probability that
  1380. * this BigInteger is prime exceeds <code>(1 - 1/2<sup>certainty</sup>)</code>.
  1381. * The execution time of this method is proportional to the value of this
  1382. * parameter.
  1383. * @return <code>true</code> if this BigInteger is probably prime,
  1384. * <code>false</code> if it's definitely composite.
  1385. */
  1386. public boolean isProbablePrime(int certainty)
  1387. {
  1388. if (certainty < 1)
  1389. return true;
  1390. if (USING_NATIVE)
  1391. return mpz.testPrimality(certainty) != 0;
  1392. /** We'll use the Rabin-Miller algorithm for doing a probabilistic
  1393. * primality test. It is fast, easy and has faster decreasing odds of a
  1394. * composite passing than with other tests. This means that this
  1395. * method will actually have a probability much greater than the
  1396. * 1 - .5^certainty specified in the JCL (p. 117), but I don't think
  1397. * anyone will complain about better performance with greater certainty.
  1398. *
  1399. * The Rabin-Miller algorithm can be found on pp. 259-261 of "Applied
  1400. * Cryptography, Second Edition" by Bruce Schneier.
  1401. */
  1402. // First rule out small prime factors
  1403. BigInteger rem = new BigInteger();
  1404. int i;
  1405. for (i = 0; i < primes.length; i++)
  1406. {
  1407. if (words == null && ival == primes[i])
  1408. return true;
  1409. divide(this, smallFixNums[primes[i] - minFixNum], null, rem, TRUNCATE);
  1410. if (rem.canonicalize().isZero())
  1411. return false;
  1412. }
  1413. // Now perform the Rabin-Miller test.
  1414. // Set b to the number of times 2 evenly divides (this - 1).
  1415. // I.e. 2^b is the largest power of 2 that divides (this - 1).
  1416. BigInteger pMinus1 = add(this, -1);
  1417. int b = pMinus1.getLowestSetBit();
  1418. // Set m such that this = 1 + 2^b * m.
  1419. BigInteger m = pMinus1.divide(valueOf(2L).pow(b));
  1420. // The HAC (Handbook of Applied Cryptography), Alfred Menezes & al. Note
  1421. // 4.49 (controlling the error probability) gives the number of trials
  1422. // for an error probability of 1/2**80, given the number of bits in the
  1423. // number to test. we shall use these numbers as is if/when 'certainty'
  1424. // is less or equal to 80, and twice as much if it's greater.
  1425. int bits = this.bitLength();
  1426. for (i = 0; i < k.length; i++)
  1427. if (bits <= k[i])
  1428. break;
  1429. int trials = t[i];
  1430. if (certainty > 80)
  1431. trials *= 2;
  1432. BigInteger z;
  1433. for (int t = 0; t < trials; t++)
  1434. {
  1435. // The HAC (Handbook of Applied Cryptography), Alfred Menezes & al.
  1436. // Remark 4.28 states: "...A strategy that is sometimes employed
  1437. // is to fix the bases a to be the first few primes instead of
  1438. // choosing them at random.
  1439. z = smallFixNums[primes[t] - minFixNum].modPow(m, this);
  1440. if (z.isOne() || z.equals(pMinus1))
  1441. continue; // Passes the test; may be prime.
  1442. for (i = 0; i < b; )
  1443. {
  1444. if (z.isOne())
  1445. return false;
  1446. i++;
  1447. if (z.equals(pMinus1))
  1448. break; // Passes the test; may be prime.
  1449. z = z.modPow(valueOf(2), this);
  1450. }
  1451. if (i == b && !z.equals(pMinus1))
  1452. return false;
  1453. }
  1454. return true;
  1455. }
  1456. private void setInvert()
  1457. {
  1458. if (words == null)
  1459. ival = ~ival;
  1460. else
  1461. {
  1462. for (int i = ival; --i >= 0; )
  1463. words[i] = ~words[i];
  1464. }
  1465. }
  1466. private void setShiftLeft(BigInteger x, int count)
  1467. {
  1468. int[] xwords;
  1469. int xlen;
  1470. if (x.words == null)
  1471. {
  1472. if (count < 32)
  1473. {
  1474. set((long) x.ival << count);
  1475. return;
  1476. }
  1477. xwords = new int[1];
  1478. xwords[0] = x.ival;
  1479. xlen = 1;
  1480. }
  1481. else
  1482. {
  1483. xwords = x.words;
  1484. xlen = x.ival;
  1485. }
  1486. int word_count = count >> 5;
  1487. count &= 31;
  1488. int new_len = xlen + word_count;
  1489. if (count == 0)
  1490. {
  1491. realloc(new_len);
  1492. for (int i = xlen; --i >= 0; )
  1493. words[i+word_count] = xwords[i];
  1494. }
  1495. else
  1496. {
  1497. new_len++;
  1498. realloc(new_len);
  1499. int shift_out = MPN.lshift(words, word_count, xwords, xlen, count);
  1500. count = 32 - count;
  1501. words[new_len-1] = (shift_out << count) >> count; // sign-extend.
  1502. }
  1503. ival = new_len;
  1504. for (int i = word_count; --i >= 0; )
  1505. words[i] = 0;
  1506. }
  1507. private void setShiftRight(BigInteger x, int count)
  1508. {
  1509. if (x.words == null)
  1510. set(count < 32 ? x.ival >> count : x.ival < 0 ? -1 : 0);
  1511. else if (count == 0)
  1512. set(x);
  1513. else
  1514. {
  1515. boolean neg = x.isNegative();
  1516. int word_count = count >> 5;
  1517. count &= 31;
  1518. int d_len = x.ival - word_count;
  1519. if (d_len <= 0)
  1520. set(neg ? -1 : 0);
  1521. else
  1522. {
  1523. if (words == null || words.length < d_len)
  1524. realloc(d_len);
  1525. MPN.rshift0 (words, x.words, word_count, d_len, count);
  1526. ival = d_len;
  1527. if (neg)
  1528. words[d_len-1] |= -2 << (31 - count);
  1529. }
  1530. }
  1531. }
  1532. private void setShift(BigInteger x, int count)
  1533. {
  1534. if (count > 0)
  1535. setShiftLeft(x, count);
  1536. else
  1537. setShiftRight(x, -count);
  1538. }
  1539. private static BigInteger shift(BigInteger x, int count)
  1540. {
  1541. if (x.words == null)
  1542. {
  1543. if (count <= 0)
  1544. return valueOf(count > -32 ? x.ival >> (-count) : x.ival < 0 ? -1 : 0);
  1545. if (count < 32)
  1546. return valueOf((long) x.ival << count);
  1547. }
  1548. if (count == 0)
  1549. return x;
  1550. BigInteger result = new BigInteger(0);
  1551. result.setShift(x, count);
  1552. return result.canonicalize();
  1553. }
  1554. public BigInteger shiftLeft(int n)
  1555. {
  1556. if (n == 0)
  1557. return this;
  1558. if (USING_NATIVE)
  1559. {
  1560. BigInteger result = new BigInteger();
  1561. if (n < 0)
  1562. mpz.shiftRight(-n, result.mpz);
  1563. else
  1564. mpz.shiftLeft(n, result.mpz);
  1565. return result;
  1566. }
  1567. return shift(this, n);
  1568. }
  1569. public BigInteger shiftRight(int n)
  1570. {
  1571. if (n == 0)
  1572. return this;
  1573. if (USING_NATIVE)
  1574. {
  1575. BigInteger result = new BigInteger();
  1576. if (n < 0)
  1577. mpz.shiftLeft(-n, result.mpz);
  1578. else
  1579. mpz.shiftRight(n, result.mpz);
  1580. return result;
  1581. }
  1582. return shift(this, -n);
  1583. }
  1584. private void format(int radix, CPStringBuilder buffer)
  1585. {
  1586. if (words == null)
  1587. buffer.append(Integer.toString(ival, radix));
  1588. else if (ival <= 2)
  1589. buffer.append(Long.toString(longValue(), radix));
  1590. else
  1591. {
  1592. boolean neg = isNegative();
  1593. int[] work;
  1594. if (neg || radix != 16)
  1595. {
  1596. work = new int[ival];
  1597. getAbsolute(work);
  1598. }
  1599. else
  1600. work = words;
  1601. int len = ival;
  1602. if (radix == 16)
  1603. {
  1604. if (neg)
  1605. buffer.append('-');
  1606. int buf_start = buffer.length();
  1607. for (int i = len; --i >= 0; )
  1608. {
  1609. int word = work[i];
  1610. for (int j = 8; --j >= 0; )
  1611. {
  1612. int hex_digit = (word >> (4 * j)) & 0xF;
  1613. // Suppress leading zeros:
  1614. if (hex_digit > 0 || buffer.length() > buf_start)
  1615. buffer.append(Character.forDigit(hex_digit, 16));
  1616. }
  1617. }
  1618. }
  1619. else
  1620. {
  1621. int i = buffer.length();
  1622. for (;;)
  1623. {
  1624. int digit = MPN.divmod_1(work, work, len, radix);
  1625. buffer.append(Character.forDigit(digit, radix));
  1626. while (len > 0 && work[len-1] == 0) len--;
  1627. if (len == 0)
  1628. break;
  1629. }
  1630. if (neg)
  1631. buffer.append('-');
  1632. /* Reverse buffer. */
  1633. int j = buffer.length() - 1;
  1634. while (i < j)
  1635. {
  1636. char tmp = buffer.charAt(i);
  1637. buffer.setCharAt(i, buffer.charAt(j));
  1638. buffer.setCharAt(j, tmp);
  1639. i++; j--;
  1640. }
  1641. }
  1642. }
  1643. }
  1644. public String toString()
  1645. {
  1646. return toString(10);
  1647. }
  1648. public String toString(int radix)
  1649. {
  1650. if (USING_NATIVE)
  1651. return mpz.toString(radix);
  1652. if (words == null)
  1653. return Integer.toString(ival, radix);
  1654. if (ival <= 2)
  1655. return Long.toString(longValue(), radix);
  1656. int buf_size = ival * (MPN.chars_per_word(radix) + 1);
  1657. CPStringBuilder buffer = new CPStringBuilder(buf_size);
  1658. format(radix, buffer);
  1659. return buffer.toString();
  1660. }
  1661. public int intValue()
  1662. {
  1663. if (USING_NATIVE)
  1664. {
  1665. int result = mpz.absIntValue();
  1666. return mpz.compare(ZERO.mpz) < 0 ? - result : result;
  1667. }
  1668. if (words == null)
  1669. return ival;
  1670. return words[0];
  1671. }
  1672. public long longValue()
  1673. {
  1674. if (USING_NATIVE)
  1675. {
  1676. long result;
  1677. result = (abs().shiftRight(32)).mpz.absIntValue();
  1678. result <<= 32;
  1679. result |= mpz.absIntValue() & 0xFFFFFFFFL;
  1680. return this.compareTo(ZERO) < 0 ? - result : result;
  1681. }
  1682. if (words == null)
  1683. return ival;
  1684. if (ival == 1)
  1685. return words[0];
  1686. return ((long)words[1] << 32) + ((long)words[0] & 0xffffffffL);
  1687. }
  1688. public int hashCode()
  1689. {
  1690. // FIXME: May not match hashcode of JDK.
  1691. if (USING_NATIVE)
  1692. {
  1693. // TODO: profile to decide whether to make it native
  1694. byte[] bytes = this.toByteArray();
  1695. int result = 0;
  1696. for (int i = 0; i < bytes.length; i++)
  1697. result ^= (bytes[i] & 0xFF) << (8 * (i % 4));
  1698. return result;
  1699. }
  1700. return words == null ? ival : (words[0] + words[ival - 1]);
  1701. }
  1702. /* Assumes x and y are both canonicalized. */
  1703. private static boolean equals(BigInteger x, BigInteger y)
  1704. {
  1705. if (USING_NATIVE)
  1706. return x.mpz.compare(y.mpz) == 0;
  1707. if (x.words == null && y.words == null)
  1708. return x.ival == y.ival;
  1709. if (x.words == null || y.words == null || x.ival != y.ival)
  1710. return false;
  1711. for (int i = x.ival; --i >= 0; )
  1712. {
  1713. if (x.words[i] != y.words[i])
  1714. return false;
  1715. }
  1716. return true;
  1717. }
  1718. /* Assumes this and obj are both canonicalized. */
  1719. public boolean equals(Object obj)
  1720. {
  1721. if (! (obj instanceof BigInteger))
  1722. return false;
  1723. return equals(this, (BigInteger) obj);
  1724. }
  1725. private static BigInteger valueOf(byte[] digits, int byte_len,
  1726. boolean negative, int radix)
  1727. {
  1728. int chars_per_word = MPN.chars_per_word(radix);
  1729. int[] words = new int[byte_len / chars_per_word + 1];
  1730. int size = MPN.set_str(words, digits, byte_len, radix);
  1731. if (size == 0)
  1732. return ZERO;
  1733. if (words[size-1] < 0)
  1734. words[size++] = 0;
  1735. if (negative)
  1736. negate(words, words, size);
  1737. return make(words, size);
  1738. }
  1739. public double doubleValue()
  1740. {
  1741. if (USING_NATIVE)
  1742. return mpz.doubleValue();
  1743. if (words == null)
  1744. return (double) ival;
  1745. if (ival <= 2)
  1746. return (double) longValue();
  1747. if (isNegative())
  1748. return neg(this).roundToDouble(0, true, false);
  1749. return roundToDouble(0, false, false);
  1750. }
  1751. public float floatValue()
  1752. {
  1753. return (float) doubleValue();
  1754. }
  1755. /** Return true if any of the lowest n bits are one.
  1756. * (false if n is negative). */
  1757. private boolean checkBits(int n)
  1758. {
  1759. if (n <= 0)
  1760. return false;
  1761. if (words == null)
  1762. return n > 31 || ((ival & ((1 << n) - 1)) != 0);
  1763. int i;
  1764. for (i = 0; i < (n >> 5) ; i++)
  1765. if (words[i] != 0)
  1766. return true;
  1767. return (n & 31) != 0 && (words[i] & ((1 << (n & 31)) - 1)) != 0;
  1768. }
  1769. /** Convert a semi-processed BigInteger to double.
  1770. * Number must be non-negative. Multiplies by a power of two, applies sign,
  1771. * and converts to double, with the usual java rounding.
  1772. * @param exp power of two, positive or negative, by which to multiply
  1773. * @param neg true if negative
  1774. * @param remainder true if the BigInteger is the result of a truncating
  1775. * division that had non-zero remainder. To ensure proper rounding in
  1776. * this case, the BigInteger must have at least 54 bits. */
  1777. private double roundToDouble(int exp, boolean neg, boolean remainder)
  1778. {
  1779. // Compute length.
  1780. int il = bitLength();
  1781. // Exponent when normalized to have decimal point directly after
  1782. // leading one. This is stored excess 1023 in the exponent bit field.
  1783. exp += il - 1;
  1784. // Gross underflow. If exp == -1075, we let the rounding
  1785. // computation determine whether it is minval or 0 (which are just
  1786. // 0x0000 0000 0000 0001 and 0x0000 0000 0000 0000 as bit
  1787. // patterns).
  1788. if (exp < -1075)
  1789. return neg ? -0.0 : 0.0;
  1790. // gross overflow
  1791. if (exp > 1023)
  1792. return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1793. // number of bits in mantissa, including the leading one.
  1794. // 53 unless it's denormalized
  1795. int ml = (exp >= -1022 ? 53 : 53 + exp + 1022);
  1796. // Get top ml + 1 bits. The extra one is for rounding.
  1797. long m;
  1798. int excess_bits = il - (ml + 1);
  1799. if (excess_bits > 0)
  1800. m = ((words == null) ? ival >> excess_bits
  1801. : MPN.rshift_long(words, ival, excess_bits));
  1802. else
  1803. m = longValue() << (- excess_bits);
  1804. // Special rounding for maxval. If the number exceeds maxval by
  1805. // any amount, even if it's less than half a step, it overflows.
  1806. if (exp == 1023 && ((m >> 1) == (1L << 53) - 1))
  1807. {
  1808. if (remainder || checkBits(il - ml))
  1809. return neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1810. else
  1811. return neg ? - Double.MAX_VALUE : Double.MAX_VALUE;
  1812. }
  1813. // Normal round-to-even rule: round up if the bit dropped is a one, and
  1814. // the bit above it or any of the bits below it is a one.
  1815. if ((m & 1) == 1
  1816. && ((m & 2) == 2 || remainder || checkBits(excess_bits)))
  1817. {
  1818. m += 2;
  1819. // Check if we overflowed the mantissa
  1820. if ((m & (1L << 54)) != 0)
  1821. {
  1822. exp++;
  1823. // renormalize
  1824. m >>= 1;
  1825. }
  1826. // Check if a denormalized mantissa was just rounded up to a
  1827. // normalized one.
  1828. else if (ml == 52 && (m & (1L << 53)) != 0)
  1829. exp++;
  1830. }
  1831. // Discard the rounding bit
  1832. m >>= 1;
  1833. long bits_sign = neg ? (1L << 63) : 0;
  1834. exp += 1023;
  1835. long bits_exp = (exp <= 0) ? 0 : ((long)exp) << 52;
  1836. long bits_mant = m & ~(1L << 52);
  1837. return Double.longBitsToDouble(bits_sign | bits_exp | bits_mant);
  1838. }
  1839. /** Copy the abolute value of this into an array of words.
  1840. * Assumes words.length >= (this.words == null ? 1 : this.ival).
  1841. * Result is zero-extended, but need not be a valid 2's complement number.
  1842. */
  1843. private void getAbsolute(int[] words)
  1844. {
  1845. int len;
  1846. if (this.words == null)
  1847. {
  1848. len = 1;
  1849. words[0] = this.ival;
  1850. }
  1851. else
  1852. {
  1853. len = this.ival;
  1854. for (int i = len; --i >= 0; )
  1855. words[i] = this.words[i];
  1856. }
  1857. if (words[len - 1] < 0)
  1858. negate(words, words, len);
  1859. for (int i = words.length; --i > len; )
  1860. words[i] = 0;
  1861. }
  1862. /** Set dest[0:len-1] to the negation of src[0:len-1].
  1863. * Return true if overflow (i.e. if src is -2**(32*len-1)).
  1864. * Ok for src==dest. */
  1865. private static boolean negate(int[] dest, int[] src, int len)
  1866. {
  1867. long carry = 1;
  1868. boolean negative = src[len-1] < 0;
  1869. for (int i = 0; i < len; i++)
  1870. {
  1871. carry += ((long) (~src[i]) & 0xffffffffL);
  1872. dest[i] = (int) carry;
  1873. carry >>= 32;
  1874. }
  1875. return (negative && dest[len-1] < 0);
  1876. }
  1877. /** Destructively set this to the negative of x.
  1878. * It is OK if x==this.*/
  1879. private void setNegative(BigInteger x)
  1880. {
  1881. int len = x.ival;
  1882. if (x.words == null)
  1883. {
  1884. if (len == Integer.MIN_VALUE)
  1885. set(- (long) len);
  1886. else
  1887. set(-len);
  1888. return;
  1889. }
  1890. realloc(len + 1);
  1891. if (negate(words, x.words, len))
  1892. words[len++] = 0;
  1893. ival = len;
  1894. }
  1895. /** Destructively negate this. */
  1896. private void setNegative()
  1897. {
  1898. setNegative(this);
  1899. }
  1900. private static BigInteger abs(BigInteger x)
  1901. {
  1902. return x.isNegative() ? neg(x) : x;
  1903. }
  1904. public BigInteger abs()
  1905. {
  1906. if (USING_NATIVE)
  1907. {
  1908. BigInteger result = new BigInteger();
  1909. mpz.abs(result.mpz);
  1910. return result;
  1911. }
  1912. return abs(this);
  1913. }
  1914. private static BigInteger neg(BigInteger x)
  1915. {
  1916. if (x.words == null && x.ival != Integer.MIN_VALUE)
  1917. return valueOf(- x.ival);
  1918. BigInteger result = new BigInteger(0);
  1919. result.setNegative(x);
  1920. return result.canonicalize();
  1921. }
  1922. public BigInteger negate()
  1923. {
  1924. if (USING_NATIVE)
  1925. {
  1926. BigInteger result = new BigInteger();
  1927. mpz.negate(result.mpz);
  1928. return result;
  1929. }
  1930. return neg(this);
  1931. }
  1932. /** Calculates ceiling(log2(this < 0 ? -this : this+1))
  1933. * See Common Lisp: the Language, 2nd ed, p. 361.
  1934. */
  1935. public int bitLength()
  1936. {
  1937. if (USING_NATIVE)
  1938. return mpz.bitLength();
  1939. if (words == null)
  1940. return MPN.intLength(ival);
  1941. return MPN.intLength(words, ival);
  1942. }
  1943. public byte[] toByteArray()
  1944. {
  1945. if (signum() == 0)
  1946. return new byte[1];
  1947. if (USING_NATIVE)
  1948. {
  1949. // the minimal number of bytes required to represent the MPI is function
  1950. // of (a) its bit-length, and (b) its sign. only when this MPI is both
  1951. // positive, and its bit-length is a multiple of 8 do we add one zero
  1952. // bit for its sign. we do this so if we construct a new MPI from the
  1953. // resulting byte array, we wouldn't mistake a positive number, whose
  1954. // bit-length is a multiple of 8, for a similar-length negative one.
  1955. int bits = bitLength();
  1956. if (bits % 8 == 0 || this.signum() == 1)
  1957. bits++;
  1958. byte[] bytes = new byte[(bits + 7) / 8];
  1959. mpz.toByteArray(bytes);
  1960. return bytes;
  1961. }
  1962. // Determine number of bytes needed. The method bitlength returns
  1963. // the size without the sign bit, so add one bit for that and then
  1964. // add 7 more to emulate the ceil function using integer math.
  1965. byte[] bytes = new byte[(bitLength() + 1 + 7) / 8];
  1966. int nbytes = bytes.length;
  1967. int wptr = 0;
  1968. int word;
  1969. // Deal with words array until one word or less is left to process.
  1970. // If BigInteger is an int, then it is in ival and nbytes will be <= 4.
  1971. while (nbytes > 4)
  1972. {
  1973. word = words[wptr++];
  1974. for (int i = 4; i > 0; --i, word >>= 8)
  1975. bytes[--nbytes] = (byte) word;
  1976. }
  1977. // Deal with the last few bytes. If BigInteger is an int, use ival.
  1978. word = (words == null) ? ival : words[wptr];
  1979. for ( ; nbytes > 0; word >>= 8)
  1980. bytes[--nbytes] = (byte) word;
  1981. return bytes;
  1982. }
  1983. /** Return the boolean opcode (for bitOp) for swapped operands.
  1984. * I.e. bitOp(swappedOp(op), x, y) == bitOp(op, y, x).
  1985. */
  1986. private static int swappedOp(int op)
  1987. {
  1988. return
  1989. "\000\001\004\005\002\003\006\007\010\011\014\015\012\013\016\017"
  1990. .charAt(op);
  1991. }
  1992. /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
  1993. private static BigInteger bitOp(int op, BigInteger x, BigInteger y)
  1994. {
  1995. switch (op)
  1996. {
  1997. case 0: return ZERO;
  1998. case 1: return x.and(y);
  1999. case 3: return x;
  2000. case 5: return y;
  2001. case 15: return valueOf(-1);
  2002. }
  2003. BigInteger result = new BigInteger();
  2004. setBitOp(result, op, x, y);
  2005. return result.canonicalize();
  2006. }
  2007. /** Do one the the 16 possible bit-wise operations of two BigIntegers. */
  2008. private static void setBitOp(BigInteger result, int op,
  2009. BigInteger x, BigInteger y)
  2010. {
  2011. if ((y.words != null) && (x.words == null || x.ival < y.ival))
  2012. {
  2013. BigInteger temp = x; x = y; y = temp;
  2014. op = swappedOp(op);
  2015. }
  2016. int xi;
  2017. int yi;
  2018. int xlen, ylen;
  2019. if (y.words == null)
  2020. {
  2021. yi = y.ival;
  2022. ylen = 1;
  2023. }
  2024. else
  2025. {
  2026. yi = y.words[0];
  2027. ylen = y.ival;
  2028. }
  2029. if (x.words == null)
  2030. {
  2031. xi = x.ival;
  2032. xlen = 1;
  2033. }
  2034. else
  2035. {
  2036. xi = x.words[0];
  2037. xlen = x.ival;
  2038. }
  2039. if (xlen > 1)
  2040. result.realloc(xlen);
  2041. int[] w = result.words;
  2042. int i = 0;
  2043. // Code for how to handle the remainder of x.
  2044. // 0: Truncate to length of y.
  2045. // 1: Copy rest of x.
  2046. // 2: Invert rest of x.
  2047. int finish = 0;
  2048. int ni;
  2049. switch (op)
  2050. {
  2051. case 0: // clr
  2052. ni = 0;
  2053. break;
  2054. case 1: // and
  2055. for (;;)
  2056. {
  2057. ni = xi & yi;
  2058. if (i+1 >= ylen) break;
  2059. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2060. }
  2061. if (yi < 0) finish = 1;
  2062. break;
  2063. case 2: // andc2
  2064. for (;;)
  2065. {
  2066. ni = xi & ~yi;
  2067. if (i+1 >= ylen) break;
  2068. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2069. }
  2070. if (yi >= 0) finish = 1;
  2071. break;
  2072. case 3: // copy x
  2073. ni = xi;
  2074. finish = 1; // Copy rest
  2075. break;
  2076. case 4: // andc1
  2077. for (;;)
  2078. {
  2079. ni = ~xi & yi;
  2080. if (i+1 >= ylen) break;
  2081. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2082. }
  2083. if (yi < 0) finish = 2;
  2084. break;
  2085. case 5: // copy y
  2086. for (;;)
  2087. {
  2088. ni = yi;
  2089. if (i+1 >= ylen) break;
  2090. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2091. }
  2092. break;
  2093. case 6: // xor
  2094. for (;;)
  2095. {
  2096. ni = xi ^ yi;
  2097. if (i+1 >= ylen) break;
  2098. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2099. }
  2100. finish = yi < 0 ? 2 : 1;
  2101. break;
  2102. case 7: // ior
  2103. for (;;)
  2104. {
  2105. ni = xi | yi;
  2106. if (i+1 >= ylen) break;
  2107. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2108. }
  2109. if (yi >= 0) finish = 1;
  2110. break;
  2111. case 8: // nor
  2112. for (;;)
  2113. {
  2114. ni = ~(xi | yi);
  2115. if (i+1 >= ylen) break;
  2116. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2117. }
  2118. if (yi >= 0) finish = 2;
  2119. break;
  2120. case 9: // eqv [exclusive nor]
  2121. for (;;)
  2122. {
  2123. ni = ~(xi ^ yi);
  2124. if (i+1 >= ylen) break;
  2125. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2126. }
  2127. finish = yi >= 0 ? 2 : 1;
  2128. break;
  2129. case 10: // c2
  2130. for (;;)
  2131. {
  2132. ni = ~yi;
  2133. if (i+1 >= ylen) break;
  2134. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2135. }
  2136. break;
  2137. case 11: // orc2
  2138. for (;;)
  2139. {
  2140. ni = xi | ~yi;
  2141. if (i+1 >= ylen) break;
  2142. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2143. }
  2144. if (yi < 0) finish = 1;
  2145. break;
  2146. case 12: // c1
  2147. ni = ~xi;
  2148. finish = 2;
  2149. break;
  2150. case 13: // orc1
  2151. for (;;)
  2152. {
  2153. ni = ~xi | yi;
  2154. if (i+1 >= ylen) break;
  2155. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2156. }
  2157. if (yi >= 0) finish = 2;
  2158. break;
  2159. case 14: // nand
  2160. for (;;)
  2161. {
  2162. ni = ~(xi & yi);
  2163. if (i+1 >= ylen) break;
  2164. w[i++] = ni; xi = x.words[i]; yi = y.words[i];
  2165. }
  2166. if (yi < 0) finish = 2;
  2167. break;
  2168. default:
  2169. case 15: // set
  2170. ni = -1;
  2171. break;
  2172. }
  2173. // Here i==ylen-1; w[0]..w[i-1] have the correct result;
  2174. // and ni contains the correct result for w[i+1].
  2175. if (i+1 == xlen)
  2176. finish = 0;
  2177. switch (finish)
  2178. {
  2179. case 0:
  2180. if (i == 0 && w == null)
  2181. {
  2182. result.ival = ni;
  2183. return;
  2184. }
  2185. w[i++] = ni;
  2186. break;
  2187. case 1: w[i] = ni; while (++i < xlen) w[i] = x.words[i]; break;
  2188. case 2: w[i] = ni; while (++i < xlen) w[i] = ~x.words[i]; break;
  2189. }
  2190. result.ival = i;
  2191. }
  2192. /** Return the logical (bit-wise) "and" of a BigInteger and an int. */
  2193. private static BigInteger and(BigInteger x, int y)
  2194. {
  2195. if (x.words == null)
  2196. return valueOf(x.ival & y);
  2197. if (y >= 0)
  2198. return valueOf(x.words[0] & y);
  2199. int len = x.ival;
  2200. int[] words = new int[len];
  2201. words[0] = x.words[0] & y;
  2202. while (--len > 0)
  2203. words[len] = x.words[len];
  2204. return make(words, x.ival);
  2205. }
  2206. /** Return the logical (bit-wise) "and" of two BigIntegers. */
  2207. public BigInteger and(BigInteger y)
  2208. {
  2209. if (USING_NATIVE)
  2210. {
  2211. int dummy = y.signum; // force NPE check
  2212. BigInteger result = new BigInteger();
  2213. mpz.and(y.mpz, result.mpz);
  2214. return result;
  2215. }
  2216. if (y.words == null)
  2217. return and(this, y.ival);
  2218. else if (words == null)
  2219. return and(y, ival);
  2220. BigInteger x = this;
  2221. if (ival < y.ival)
  2222. {
  2223. BigInteger temp = this; x = y; y = temp;
  2224. }
  2225. int i;
  2226. int len = y.isNegative() ? x.ival : y.ival;
  2227. int[] words = new int[len];
  2228. for (i = 0; i < y.ival; i++)
  2229. words[i] = x.words[i] & y.words[i];
  2230. for ( ; i < len; i++)
  2231. words[i] = x.words[i];
  2232. return make(words, len);
  2233. }
  2234. /** Return the logical (bit-wise) "(inclusive) or" of two BigIntegers. */
  2235. public BigInteger or(BigInteger y)
  2236. {
  2237. if (USING_NATIVE)
  2238. {
  2239. int dummy = y.signum; // force NPE check
  2240. BigInteger result = new BigInteger();
  2241. mpz.or(y.mpz, result.mpz);
  2242. return result;
  2243. }
  2244. return bitOp(7, this, y);
  2245. }
  2246. /** Return the logical (bit-wise) "exclusive or" of two BigIntegers. */
  2247. public BigInteger xor(BigInteger y)
  2248. {
  2249. if (USING_NATIVE)
  2250. {
  2251. int dummy = y.signum; // force NPE check
  2252. BigInteger result = new BigInteger();
  2253. mpz.xor(y.mpz, result.mpz);
  2254. return result;
  2255. }
  2256. return bitOp(6, this, y);
  2257. }
  2258. /** Return the logical (bit-wise) negation of a BigInteger. */
  2259. public BigInteger not()
  2260. {
  2261. if (USING_NATIVE)
  2262. {
  2263. BigInteger result = new BigInteger();
  2264. mpz.not(result.mpz);
  2265. return result;
  2266. }
  2267. return bitOp(12, this, ZERO);
  2268. }
  2269. public BigInteger andNot(BigInteger val)
  2270. {
  2271. if (USING_NATIVE)
  2272. {
  2273. int dummy = val.signum; // force NPE check
  2274. BigInteger result = new BigInteger();
  2275. mpz.andNot(val.mpz, result.mpz);
  2276. return result;
  2277. }
  2278. return and(val.not());
  2279. }
  2280. public BigInteger clearBit(int n)
  2281. {
  2282. if (n < 0)
  2283. throw new ArithmeticException();
  2284. if (USING_NATIVE)
  2285. {
  2286. BigInteger result = new BigInteger();
  2287. mpz.setBit(n, false, result.mpz);
  2288. return result;
  2289. }
  2290. return and(ONE.shiftLeft(n).not());
  2291. }
  2292. public BigInteger setBit(int n)
  2293. {
  2294. if (n < 0)
  2295. throw new ArithmeticException();
  2296. if (USING_NATIVE)
  2297. {
  2298. BigInteger result = new BigInteger();
  2299. mpz.setBit(n, true, result.mpz);
  2300. return result;
  2301. }
  2302. return or(ONE.shiftLeft(n));
  2303. }
  2304. public boolean testBit(int n)
  2305. {
  2306. if (n < 0)
  2307. throw new ArithmeticException();
  2308. if (USING_NATIVE)
  2309. return mpz.testBit(n) != 0;
  2310. return !and(ONE.shiftLeft(n)).isZero();
  2311. }
  2312. public BigInteger flipBit(int n)
  2313. {
  2314. if (n < 0)
  2315. throw new ArithmeticException();
  2316. if (USING_NATIVE)
  2317. {
  2318. BigInteger result = new BigInteger();
  2319. mpz.flipBit(n, result.mpz);
  2320. return result;
  2321. }
  2322. return xor(ONE.shiftLeft(n));
  2323. }
  2324. public int getLowestSetBit()
  2325. {
  2326. if (USING_NATIVE)
  2327. return mpz.compare(ZERO.mpz) == 0 ? -1 : mpz.lowestSetBit();
  2328. if (isZero())
  2329. return -1;
  2330. if (words == null)
  2331. return MPN.findLowestBit(ival);
  2332. else
  2333. return MPN.findLowestBit(words);
  2334. }
  2335. // bit4count[I] is number of '1' bits in I.
  2336. private static final byte[] bit4_count = { 0, 1, 1, 2, 1, 2, 2, 3,
  2337. 1, 2, 2, 3, 2, 3, 3, 4};
  2338. private static int bitCount(int i)
  2339. {
  2340. int count = 0;
  2341. while (i != 0)
  2342. {
  2343. count += bit4_count[i & 15];
  2344. i >>>= 4;
  2345. }
  2346. return count;
  2347. }
  2348. private static int bitCount(int[] x, int len)
  2349. {
  2350. int count = 0;
  2351. while (--len >= 0)
  2352. count += bitCount(x[len]);
  2353. return count;
  2354. }
  2355. /** Count one bits in a BigInteger.
  2356. * If argument is negative, count zero bits instead. */
  2357. public int bitCount()
  2358. {
  2359. if (USING_NATIVE)
  2360. return mpz.bitCount();
  2361. int i, x_len;
  2362. int[] x_words = words;
  2363. if (x_words == null)
  2364. {
  2365. x_len = 1;
  2366. i = bitCount(ival);
  2367. }
  2368. else
  2369. {
  2370. x_len = ival;
  2371. i = bitCount(x_words, x_len);
  2372. }
  2373. return isNegative() ? x_len * 32 - i : i;
  2374. }
  2375. private void readObject(ObjectInputStream s)
  2376. throws IOException, ClassNotFoundException
  2377. {
  2378. if (USING_NATIVE)
  2379. {
  2380. mpz = new GMP();
  2381. s.defaultReadObject();
  2382. if (signum != 0)
  2383. mpz.fromByteArray(magnitude);
  2384. // else it's zero and we need to do nothing
  2385. }
  2386. else
  2387. {
  2388. s.defaultReadObject();
  2389. if (magnitude.length == 0 || signum == 0)
  2390. {
  2391. this.ival = 0;
  2392. this.words = null;
  2393. }
  2394. else
  2395. {
  2396. words = byteArrayToIntArray(magnitude, signum < 0 ? -1 : 0);
  2397. BigInteger result = make(words, words.length);
  2398. this.ival = result.ival;
  2399. this.words = result.words;
  2400. }
  2401. }
  2402. }
  2403. private void writeObject(ObjectOutputStream s)
  2404. throws IOException, ClassNotFoundException
  2405. {
  2406. signum = signum();
  2407. magnitude = signum == 0 ? new byte[0] : toByteArray();
  2408. s.defaultWriteObject();
  2409. magnitude = null; // not needed anymore
  2410. }
  2411. // inner class(es) ..........................................................
  2412. }