UNPKG

50.5 kBJavaScriptView Raw
1////////////////////////////////////////////////////////////////////////////////////////
2// Big Integer Library v. 5.5
3// Created 2000, last modified 2013
4// Leemon Baird
5// www.leemon.com
6//
7// Version history:
8// v 5.5 17 Mar 2013
9// - two lines of a form like "if (x<0) x+=n" had the "if" changed to "while" to
10// handle the case when x<-n. (Thanks to James Ansell for finding that bug)
11// v 5.4 3 Oct 2009
12// - added "var i" to greaterShift() so i is not global. (Thanks to PŽter Szab— for finding that bug)
13//
14// v 5.3 21 Sep 2009
15// - added randProbPrime(k) for probable primes
16// - unrolled loop in mont_ (slightly faster)
17// - millerRabin now takes a bigInt parameter rather than an int
18//
19// v 5.2 15 Sep 2009
20// - fixed capitalization in call to int2bigInt in randBigInt
21// (thanks to Emili Evripidou, Reinhold Behringer, and Samuel Macaleese for finding that bug)
22//
23// v 5.1 8 Oct 2007
24// - renamed inverseModInt_ to inverseModInt since it doesn't change its parameters
25// - added functions GCD and randBigInt, which call GCD_ and randBigInt_
26// - fixed a bug found by Rob Visser (see comment with his name below)
27// - improved comments
28//
29// This file is public domain. You can use it for any purpose without restriction.
30// I do not guarantee that it is correct, so use it at your own risk. If you use
31// it for something interesting, I'd appreciate hearing about it. If you find
32// any bugs or make any improvements, I'd appreciate hearing about those too.
33// It would also be nice if my name and URL were left in the comments. But none
34// of that is required.
35//
36// This code defines a bigInt library for arbitrary-precision integers.
37// A bigInt is an array of integers storing the value in chunks of bpe bits,
38// little endian (buff[0] is the least significant word).
39// Negative bigInts are stored two's complement. Almost all the functions treat
40// bigInts as nonnegative. The few that view them as two's complement say so
41// in their comments. Some functions assume their parameters have at least one
42// leading zero element. Functions with an underscore at the end of the name put
43// their answer into one of the arrays passed in, and have unpredictable behavior
44// in case of overflow, so the caller must make sure the arrays are big enough to
45// hold the answer. But the average user should never have to call any of the
46// underscored functions. Each important underscored function has a wrapper function
47// of the same name without the underscore that takes care of the details for you.
48// For each underscored function where a parameter is modified, that same variable
49// must not be used as another argument too. So, you cannot square x by doing
50// multMod_(x,x,n). You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n).
51// Or simply use the multMod(x,x,n) function without the underscore, where
52// such issues never arise, because non-underscored functions never change
53// their parameters; they always allocate new memory for the answer that is returned.
54//
55// These functions are designed to avoid frequent dynamic memory allocation in the inner loop.
56// For most functions, if it needs a BigInt as a local variable it will actually use
57// a global, and will only allocate to it only when it's not the right size. This ensures
58// that when a function is called repeatedly with same-sized parameters, it only allocates
59// memory on the first call.
60//
61// Note that for cryptographic purposes, the calls to Math.random() must
62// be replaced with calls to a better pseudorandom number generator.
63//
64// In the following, "bigInt" means a bigInt with at least one leading zero element,
65// and "integer" means a nonnegative integer less than radix. In some cases, integer
66// can be negative. Negative bigInts are 2s complement.
67//
68// The following functions do not modify their inputs.
69// Those returning a bigInt, string, or Array will dynamically allocate memory for that value.
70// Those returning a boolean will return the integer 0 (false) or 1 (true).
71// Those returning boolean or int will not allocate memory except possibly on the first
72// time they're called with a given parameter size.
73//
74// bigInt add(x,y) //return (x+y) for bigInts x and y.
75// bigInt addInt(x,n) //return (x+n) where x is a bigInt and n is an integer.
76// string bigInt2str(x,base) //return a string form of bigInt x in a given base, with 2 <= base <= 95
77// int bitSize(x) //return how many bits long the bigInt x is, not counting leading zeros
78// bigInt dup(x) //return a copy of bigInt x
79// boolean equals(x,y) //is the bigInt x equal to the bigint y?
80// boolean equalsInt(x,y) //is bigint x equal to integer y?
81// bigInt expand(x,n) //return a copy of x with at least n elements, adding leading zeros if needed
82// Array findPrimes(n) //return array of all primes less than integer n
83// bigInt GCD(x,y) //return greatest common divisor of bigInts x and y (each with same number of elements).
84// boolean greater(x,y) //is x>y? (x and y are nonnegative bigInts)
85// boolean greaterShift(x,y,shift)//is (x <<(shift*bpe)) > y?
86// bigInt int2bigInt(t,n,m) //return a bigInt equal to integer t, with at least n bits and m array elements
87// bigInt inverseMod(x,n) //return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
88// int inverseModInt(x,n) //return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
89// boolean isZero(x) //is the bigInt x equal to zero?
90// boolean millerRabin(x,b) //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1<b<x)
91// boolean millerRabinInt(x,b) //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is int, 1<b<x)
92// bigInt mod(x,n) //return a new bigInt equal to (x mod n) for bigInts x and n.
93// int modInt(x,n) //return x mod n for bigInt x and integer n.
94// bigInt mult(x,y) //return x*y for bigInts x and y. This is faster when y<x.
95// bigInt multMod(x,y,n) //return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
96// boolean negative(x) //is bigInt x negative?
97// bigInt powMod(x,y,n) //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n.
98// bigInt randBigInt(n,s) //return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1.
99// bigInt randTruePrime(k) //return a new, random, k-bit, true prime bigInt using Maurer's algorithm.
100// bigInt randProbPrime(k) //return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80).
101// bigInt str2bigInt(s,b,n,m) //return a bigInt for number represented in string s in base b with at least n bits and m array elements
102// bigInt sub(x,y) //return (x-y) for bigInts x and y. Negative answers will be 2s complement
103// bigInt trim(x,k) //return a copy of x with exactly k leading zero elements
104//
105//
106// The following functions each have a non-underscored version, which most users should call instead.
107// These functions each write to a single parameter, and the caller is responsible for ensuring the array
108// passed in is large enough to hold the result.
109//
110// void addInt_(x,n) //do x=x+n where x is a bigInt and n is an integer
111// void add_(x,y) //do x=x+y for bigInts x and y
112// void copy_(x,y) //do x=y on bigInts x and y
113// void copyInt_(x,n) //do x=n on bigInt x and integer n
114// void GCD_(x,y) //set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array).
115// boolean inverseMod_(x,n) //do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
116// void mod_(x,n) //do x=x mod n for bigInts x and n. (This never overflows its array).
117// void mult_(x,y) //do x=x*y for bigInts x and y.
118// void multMod_(x,y,n) //do x=x*y mod n for bigInts x,y,n.
119// void powMod_(x,y,n) //do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1.
120// void randBigInt_(b,n,s) //do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1.
121// void randTruePrime_(ans,k) //do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
122// void sub_(x,y) //do x=x-y for bigInts x and y. Negative answers will be 2s complement.
123//
124// The following functions do NOT have a non-underscored version.
125// They each write a bigInt result to one or more parameters. The caller is responsible for
126// ensuring the arrays passed in are large enough to hold the results.
127//
128// void addShift_(x,y,ys) //do x=x+(y<<(ys*bpe))
129// void carry_(x) //do carries and borrows so each element of the bigInt x fits in bpe bits.
130// void divide_(x,y,q,r) //divide x by y giving quotient q and remainder r
131// int divInt_(x,n) //do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array).
132// int eGCD_(x,y,d,a,b) //sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y
133// void halve_(x) //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array).
134// void leftShift_(x,n) //left shift bigInt x by n bits. n<bpe.
135// void linComb_(x,y,a,b) //do x=a*x+b*y for bigInts x and y and integers a and b
136// void linCombShift_(x,y,b,ys) //do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
137// void mont_(x,y,n,np) //Montgomery multiplication (see comments where the function is defined)
138// void multInt_(x,n) //do x=x*n where x is a bigInt and n is an integer.
139// void rightShift_(x,n) //right shift bigInt x by n bits. 0 <= n < bpe. (This never overflows its array).
140// void squareMod_(x,n) //do x=x*x mod n for bigInts x,n
141// void subShift_(x,y,ys) //do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement.
142//
143// The following functions are based on algorithms from the _Handbook of Applied Cryptography_
144// powMod_() = algorithm 14.94, Montgomery exponentiation
145// eGCD_,inverseMod_() = algorithm 14.61, Binary extended GCD_
146// GCD_() = algorothm 14.57, Lehmer's algorithm
147// mont_() = algorithm 14.36, Montgomery multiplication
148// divide_() = algorithm 14.20 Multiple-precision division
149// squareMod_() = algorithm 14.16 Multiple-precision squaring
150// randTruePrime_() = algorithm 4.62, Maurer's algorithm
151// millerRabin() = algorithm 4.24, Miller-Rabin algorithm
152//
153// Profiling shows:
154// randTruePrime_() spends:
155// 10% of its time in calls to powMod_()
156// 85% of its time in calls to millerRabin()
157// millerRabin() spends:
158// 99% of its time in calls to powMod_() (always with a base of 2)
159// powMod_() spends:
160// 94% of its time in calls to mont_() (almost always with x==y)
161//
162// This suggests there are several ways to speed up this library slightly:
163// - convert powMod_ to use a Montgomery form of k-ary window (or maybe a Montgomery form of sliding window)
164// -- this should especially focus on being fast when raising 2 to a power mod n
165// - convert randTruePrime_() to use a minimum r of 1/3 instead of 1/2 with the appropriate change to the test
166// - tune the parameters in randTruePrime_(), including c, m, and recLimit
167// - speed up the single loop in mont_() that takes 95% of the runtime, perhaps by reducing checking
168// within the loop when all the parameters are the same length.
169//
170// There are several ideas that look like they wouldn't help much at all:
171// - replacing trial division in randTruePrime_() with a sieve (that speeds up something taking almost no time anyway)
172// - increase bpe from 15 to 30 (that would help if we had a 32*32->64 multiplier, but not with JavaScript's 32*32->32)
173// - speeding up mont_(x,y,n,np) when x==y by doing a non-modular, non-Montgomery square
174// followed by a Montgomery reduction. The intermediate answer will be twice as long as x, so that
175// method would be slower. This is unfortunate because the code currently spends almost all of its time
176// doing mont_(x,x,...), both for randTruePrime_() and powMod_(). A faster method for Montgomery squaring
177// would have a large impact on the speed of randTruePrime_() and powMod_(). HAC has a couple of poorly-worded
178// sentences that seem to imply it's faster to do a non-modular square followed by a single
179// Montgomery reduction, but that's obviously wrong.
180////////////////////////////////////////////////////////////////////////////////////////
181
182//globals
183export var bpe = 0; //bits stored per array element
184var mask = 0; //AND this with an array element to chop it down to bpe bits
185var radix = mask + 1; //equals 2^bpe. A single 1 bit to the left of the last bit of mask.
186
187//the digits for converting to different bases
188var digitsStr = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\\'\"+-';
189
190//initialize the global variables
191for (bpe = 0; 1 << bpe + 1 > 1 << bpe; bpe++); //bpe=number of bits in the mantissa on this platform
192bpe >>= 1; //bpe=number of bits in one element of the array representing the bigInt
193mask = (1 << bpe) - 1; //AND the mask with an integer to get its bpe least significant bits
194radix = mask + 1; //2^bpe. a single 1 bit to the left of the first bit of mask
195export var one = int2bigInt(1, 1, 1); //constant used in powMod_()
196
197//the following global variables are scratchpad memory to
198//reduce dynamic memory allocation in the inner loop
199var t = new Array(0);
200var ss = t; //used in mult_()
201var s0 = t; //used in multMod_(), squareMod_()
202var s1 = t; //used in powMod_(), multMod_(), squareMod_()
203var s2 = t; //used in powMod_(), multMod_()
204var s3 = t; //used in powMod_()
205var s4 = t,
206 s5 = t; //used in mod_()
207var s6 = t; //used in bigInt2str()
208var s7 = t; //used in powMod_()
209var T = t; //used in GCD_()
210var sa = t; //used in mont_()
211var mr_x1 = t,
212 mr_r = t,
213 mr_a = t,
214 //used in millerRabin()
215eg_v = t,
216 eg_u = t,
217 eg_A = t,
218 eg_B = t,
219 eg_C = t,
220 eg_D = t,
221 //used in eGCD_(), inverseMod_()
222md_q1 = t,
223 md_q2 = t,
224 md_q3 = t,
225 md_r = t,
226 md_r1 = t,
227 md_r2 = t,
228 md_tt = t,
229 //used in mod_()
230
231primes = t,
232 pows = t,
233 s_i = t,
234 s_i2 = t,
235 s_R = t,
236 s_rm = t,
237 s_q = t,
238 s_n1 = t,
239 s_a = t,
240 s_r2 = t,
241 s_n = t,
242 s_b = t,
243 s_d = t,
244 s_x1 = t,
245 s_x2 = t,
246 s_aa = t,
247 //used in randTruePrime_()
248
249rpprb = t; //used in randProbPrimeRounds() (which also uses "primes")
250
251////////////////////////////////////////////////////////////////////////////////////////
252
253var k, buff;
254
255//return array of all primes less than integer n
256function findPrimes(n) {
257 var i, s, p, ans;
258 s = new Array(n);
259 for (i = 0; i < n; i++) s[i] = 0;
260 s[0] = 2;
261 p = 0; //first p elements of s are primes, the rest are a sieve
262 for (; s[p] < n;) {
263 //s[p] is the pth prime
264 for (i = s[p] * s[p]; i < n; i += s[p]) //mark multiples of s[p]
265 s[i] = 1;
266 p++;
267 s[p] = s[p - 1] + 1;
268 for (; s[p] < n && s[s[p]]; s[p]++); //find next prime (where s[p]==0)
269 }
270 ans = new Array(p);
271 for (i = 0; i < p; i++) ans[i] = s[i];
272 return ans;
273}
274
275//does a single round of Miller-Rabin base b consider x to be a possible prime?
276//x is a bigInt, and b is an integer, with b<x
277function millerRabinInt(x, b) {
278 if (mr_x1.length != x.length) {
279 mr_x1 = dup(x);
280 mr_r = dup(x);
281 mr_a = dup(x);
282 }
283
284 copyInt_(mr_a, b);
285 return millerRabin(x, mr_a);
286}
287
288//does a single round of Miller-Rabin base b consider x to be a possible prime?
289//x and b are bigInts with b<x
290function millerRabin(x, b) {
291 var i, j, k, s;
292
293 if (mr_x1.length != x.length) {
294 mr_x1 = dup(x);
295 mr_r = dup(x);
296 mr_a = dup(x);
297 }
298
299 copy_(mr_a, b);
300 copy_(mr_r, x);
301 copy_(mr_x1, x);
302
303 addInt_(mr_r, -1);
304 addInt_(mr_x1, -1);
305
306 //s=the highest power of two that divides mr_r
307 k = 0;
308 for (i = 0; i < mr_r.length; i++) for (j = 1; j < mask; j <<= 1) if (x[i] & j) {
309 s = k < mr_r.length + bpe ? k : 0;
310 i = mr_r.length;
311 j = mask;
312 } else k++;
313
314 if (s) rightShift_(mr_r, s);
315
316 powMod_(mr_a, mr_r, x);
317
318 if (!equalsInt(mr_a, 1) && !equals(mr_a, mr_x1)) {
319 j = 1;
320 while (j <= s - 1 && !equals(mr_a, mr_x1)) {
321 squareMod_(mr_a, x);
322 if (equalsInt(mr_a, 1)) {
323 return 0;
324 }
325 j++;
326 }
327 if (!equals(mr_a, mr_x1)) {
328 return 0;
329 }
330 }
331 return 1;
332}
333
334//returns how many bits long the bigInt is, not counting leading zeros.
335function bitSize(x) {
336 var j, z, w;
337 for (j = x.length - 1; x[j] == 0 && j > 0; j--);
338 for (z = 0, w = x[j]; w; w >>= 1, z++);
339 z += bpe * j;
340 return z;
341}
342
343//return a copy of x with at least n elements, adding leading zeros if needed
344function expand(x, n) {
345 var ans = int2bigInt(0, (x.length > n ? x.length : n) * bpe, 0);
346 copy_(ans, x);
347 return ans;
348}
349
350//return a k-bit true random prime using Maurer's algorithm.
351function randTruePrime(k) {
352 var ans = int2bigInt(0, k, 0);
353 randTruePrime_(ans, k);
354 return trim(ans, 1);
355}
356
357//return a k-bit random probable prime with probability of error < 2^-80
358function randProbPrime(k) {
359 if (k >= 600) return randProbPrimeRounds(k, 2); //numbers from HAC table 4.3
360 if (k >= 550) return randProbPrimeRounds(k, 4);
361 if (k >= 500) return randProbPrimeRounds(k, 5);
362 if (k >= 400) return randProbPrimeRounds(k, 6);
363 if (k >= 350) return randProbPrimeRounds(k, 7);
364 if (k >= 300) return randProbPrimeRounds(k, 9);
365 if (k >= 250) return randProbPrimeRounds(k, 12); //numbers from HAC table 4.4
366 if (k >= 200) return randProbPrimeRounds(k, 15);
367 if (k >= 150) return randProbPrimeRounds(k, 18);
368 if (k >= 100) return randProbPrimeRounds(k, 27);
369 return randProbPrimeRounds(k, 40); //number from HAC remark 4.26 (only an estimate)
370}
371
372//return a k-bit probable random prime using n rounds of Miller Rabin (after trial division with small primes)
373function randProbPrimeRounds(k, n) {
374 var ans, i, divisible, B;
375 B = 30000; //B is largest prime to use in trial division
376 ans = int2bigInt(0, k, 0);
377
378 //optimization: try larger and smaller B to find the best limit.
379
380 if (primes.length == 0) primes = findPrimes(30000); //check for divisibility by primes <=30000
381
382 if (rpprb.length != ans.length) rpprb = dup(ans);
383
384 for (;;) {
385 //keep trying random values for ans until one appears to be prime
386 //optimization: pick a random number times L=2*3*5*...*p, plus a
387 // random element of the list of all numbers in [0,L) not divisible by any prime up to p.
388 // This can reduce the amount of random number generation.
389
390 randBigInt_(ans, k, 0); //ans = a random odd number to check
391 ans[0] |= 1;
392 divisible = 0;
393
394 //check ans for divisibility by small primes up to B
395 for (i = 0; i < primes.length && primes[i] <= B; i++) if (modInt(ans, primes[i]) == 0 && !equalsInt(ans, primes[i])) {
396 divisible = 1;
397 break;
398 }
399
400 //optimization: change millerRabin so the base can be bigger than the number being checked, then eliminate the while here.
401
402 //do n rounds of Miller Rabin, with random bases less than ans
403 for (i = 0; i < n && !divisible; i++) {
404 randBigInt_(rpprb, k, 0);
405 while (!greater(ans, rpprb)) //pick a random rpprb that's < ans
406 randBigInt_(rpprb, k, 0);
407 if (!millerRabin(ans, rpprb)) divisible = 1;
408 }
409
410 if (!divisible) return ans;
411 }
412}
413
414//return a new bigInt equal to (x mod n) for bigInts x and n.
415function mod(x, n) {
416 var ans = dup(x);
417 mod_(ans, n);
418 return trim(ans, 1);
419}
420
421//return (x+n) where x is a bigInt and n is an integer.
422function addInt(x, n) {
423 var ans = expand(x, x.length + 1);
424 addInt_(ans, n);
425 return trim(ans, 1);
426}
427
428//return x*y for bigInts x and y. This is faster when y<x.
429function mult(x, y) {
430 var ans = expand(x, x.length + y.length);
431 mult_(ans, y);
432 return trim(ans, 1);
433}
434
435//return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n.
436export function powMod(x, y, n) {
437 var ans = expand(x, n.length);
438 powMod_(ans, trim(y, 2), trim(n, 2), 0); //this should work without the trim, but doesn't
439 return trim(ans, 1);
440}
441
442//return (x-y) for bigInts x and y. Negative answers will be 2s complement
443function sub(x, y) {
444 var ans = expand(x, x.length > y.length ? x.length + 1 : y.length + 1);
445 sub_(ans, y);
446 return trim(ans, 1);
447}
448
449//return (x+y) for bigInts x and y.
450function add(x, y) {
451 var ans = expand(x, x.length > y.length ? x.length + 1 : y.length + 1);
452 add_(ans, y);
453 return trim(ans, 1);
454}
455
456//return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
457function inverseMod(x, n) {
458 var ans = expand(x, n.length);
459 var s;
460 s = inverseMod_(ans, n);
461 return s ? trim(ans, 1) : null;
462}
463
464//return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
465function multMod(x, y, n) {
466 var ans = expand(x, n.length);
467 multMod_(ans, y, n);
468 return trim(ans, 1);
469}
470
471//generate a k-bit true random prime using Maurer's algorithm,
472//and put it into ans. The bigInt ans must be large enough to hold it.
473function randTruePrime_(ans, k) {
474 var c, m, pm, dd, j, r, B, divisible, z, zz, recSize;
475
476 if (primes.length == 0) primes = findPrimes(30000); //check for divisibility by primes <=30000
477
478 if (pows.length == 0) {
479 pows = new Array(512);
480 for (j = 0; j < 512; j++) {
481 pows[j] = Math.pow(2, j / 511. - 1.);
482 }
483 }
484
485 //c and m should be tuned for a particular machine and value of k, to maximize speed
486 c = 0.1; //c=0.1 in HAC
487 m = 20; //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
488 recLimit = 20; //stop recursion when k <=recLimit. Must have recLimit >= 2
489
490 if (s_i2.length != ans.length) {
491 s_i2 = dup(ans);
492 s_R = dup(ans);
493 s_n1 = dup(ans);
494 s_r2 = dup(ans);
495 s_d = dup(ans);
496 s_x1 = dup(ans);
497 s_x2 = dup(ans);
498 s_b = dup(ans);
499 s_n = dup(ans);
500 s_i = dup(ans);
501 s_rm = dup(ans);
502 s_q = dup(ans);
503 s_a = dup(ans);
504 s_aa = dup(ans);
505 }
506
507 if (k <= recLimit) {
508 //generate small random primes by trial division up to its square root
509 pm = (1 << (k + 2 >> 1)) - 1; //pm is binary number with all ones, just over sqrt(2^k)
510 copyInt_(ans, 0);
511 for (dd = 1; dd;) {
512 dd = 0;
513 ans[0] = 1 | 1 << k - 1 | Math.floor(Math.random() * (1 << k)); //random, k-bit, odd integer, with msb 1
514 for (j = 1; j < primes.length && (primes[j] & pm) == primes[j]; j++) {
515 //trial division by all primes 3...sqrt(2^k)
516 if (0 == ans[0] % primes[j]) {
517 dd = 1;
518 break;
519 }
520 }
521 }
522 carry_(ans);
523 return;
524 }
525
526 B = c * k * k; //try small primes up to B (or all the primes[] array if the largest is less than B).
527 if (k > 2 * m) //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
528 for (r = 1; k - k * r <= m;) r = pows[Math.floor(Math.random() * 512)]; //r=Math.pow(2,Math.random()-1);
529 else r = .5;
530
531 //simulation suggests the more complex algorithm using r=.333 is only slightly faster.
532
533 recSize = Math.floor(r * k) + 1;
534
535 randTruePrime_(s_q, recSize);
536 copyInt_(s_i2, 0);
537 s_i2[Math.floor((k - 2) / bpe)] |= 1 << (k - 2) % bpe; //s_i2=2^(k-2)
538 divide_(s_i2, s_q, s_i, s_rm); //s_i=floor((2^(k-1))/(2q))
539
540 z = bitSize(s_i);
541
542 for (;;) {
543 for (;;) {
544 //generate z-bit numbers until one falls in the range [0,s_i-1]
545 randBigInt_(s_R, z, 0);
546 if (greater(s_i, s_R)) break;
547 } //now s_R is in the range [0,s_i-1]
548 addInt_(s_R, 1); //now s_R is in the range [1,s_i]
549 add_(s_R, s_i); //now s_R is in the range [s_i+1,2*s_i]
550
551 copy_(s_n, s_q);
552 mult_(s_n, s_R);
553 multInt_(s_n, 2);
554 addInt_(s_n, 1); //s_n=2*s_R*s_q+1
555
556 copy_(s_r2, s_R);
557 multInt_(s_r2, 2); //s_r2=2*s_R
558
559 //check s_n for divisibility by small primes up to B
560 for (divisible = 0, j = 0; j < primes.length && primes[j] < B; j++) if (modInt(s_n, primes[j]) == 0 && !equalsInt(s_n, primes[j])) {
561 divisible = 1;
562 break;
563 }
564
565 if (!divisible) //if it passes small primes check, then try a single Miller-Rabin base 2
566 if (!millerRabinInt(s_n, 2)) //this line represents 75% of the total runtime for randTruePrime_
567 divisible = 1;
568
569 if (!divisible) {
570 //if it passes that test, continue checking s_n
571 addInt_(s_n, -3);
572 for (j = s_n.length - 1; s_n[j] == 0 && j > 0; j--); //strip leading zeros
573 for (zz = 0, w = s_n[j]; w; w >>= 1, zz++);
574 zz += bpe * j; //zz=number of bits in s_n, ignoring leading zeros
575 for (;;) {
576 //generate z-bit numbers until one falls in the range [0,s_n-1]
577 randBigInt_(s_a, zz, 0);
578 if (greater(s_n, s_a)) break;
579 } //now s_a is in the range [0,s_n-1]
580 addInt_(s_n, 3); //now s_a is in the range [0,s_n-4]
581 addInt_(s_a, 2); //now s_a is in the range [2,s_n-2]
582 copy_(s_b, s_a);
583 copy_(s_n1, s_n);
584 addInt_(s_n1, -1);
585 powMod_(s_b, s_n1, s_n); //s_b=s_a^(s_n-1) modulo s_n
586 addInt_(s_b, -1);
587 if (isZero(s_b)) {
588 copy_(s_b, s_a);
589 powMod_(s_b, s_r2, s_n);
590 addInt_(s_b, -1);
591 copy_(s_aa, s_n);
592 copy_(s_d, s_b);
593 GCD_(s_d, s_n); //if s_b and s_n are relatively prime, then s_n is a prime
594 if (equalsInt(s_d, 1)) {
595 copy_(ans, s_aa);
596 return; //if we've made it this far, then s_n is absolutely guaranteed to be prime
597 }
598 }
599 }
600 }
601}
602
603//Return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1.
604function randBigInt(n, s) {
605 var a, b;
606 a = Math.floor((n - 1) / bpe) + 2; //# array elements to hold the BigInt with a leading 0 element
607 b = int2bigInt(0, 0, a);
608 randBigInt_(b, n, s);
609 return b;
610}
611
612//Set b to an n-bit random BigInt. If s=1, then the most significant of those n bits is set to 1.
613//Array b must be big enough to hold the result. Must have n>=1
614function randBigInt_(b, n, s) {
615 var i, a;
616 for (i = 0; i < b.length; i++) b[i] = 0;
617 a = Math.floor((n - 1) / bpe) + 1; //# array elements to hold the BigInt
618 for (i = 0; i < a; i++) {
619 b[i] = Math.floor(Math.random() * (1 << bpe - 1));
620 }
621 b[a - 1] &= (2 << (n - 1) % bpe) - 1;
622 if (s == 1) b[a - 1] |= 1 << (n - 1) % bpe;
623}
624
625//Return the greatest common divisor of bigInts x and y (each with same number of elements).
626function GCD(x, y) {
627 var xc, yc;
628 xc = dup(x);
629 yc = dup(y);
630 GCD_(xc, yc);
631 return xc;
632}
633
634//set x to the greatest common divisor of bigInts x and y (each with same number of elements).
635//y is destroyed.
636function GCD_(x, y) {
637 var i, xp, yp, A, B, C, D, q, sing;
638 if (T.length != x.length) T = dup(x);
639
640 sing = 1;
641 while (sing) {
642 //while y has nonzero elements other than y[0]
643 sing = 0;
644 for (i = 1; i < y.length; i++) //check if y has nonzero elements other than 0
645 if (y[i]) {
646 sing = 1;
647 break;
648 }
649 if (!sing) break; //quit when y all zero elements except possibly y[0]
650
651 for (i = x.length; !x[i] && i >= 0; i--); //find most significant element of x
652 xp = x[i];
653 yp = y[i];
654 A = 1;B = 0;C = 0;D = 1;
655 while (yp + C && yp + D) {
656 q = Math.floor((xp + A) / (yp + C));
657 qp = Math.floor((xp + B) / (yp + D));
658 if (q != qp) break;
659 t = A - q * C;A = C;C = t; // do (A,B,xp, C,D,yp) = (C,D,yp, A,B,xp) - q*(0,0,0, C,D,yp)
660 t = B - q * D;B = D;D = t;
661 t = xp - q * yp;xp = yp;yp = t;
662 }
663 if (B) {
664 copy_(T, x);
665 linComb_(x, y, A, B); //x=A*x+B*y
666 linComb_(y, T, D, C); //y=D*y+C*T
667 } else {
668 mod_(x, y);
669 copy_(T, x);
670 copy_(x, y);
671 copy_(y, T);
672 }
673 }
674 if (y[0] == 0) return;
675 t = modInt(x, y[0]);
676 copyInt_(x, y[0]);
677 y[0] = t;
678 while (y[0]) {
679 x[0] %= y[0];
680 t = x[0];x[0] = y[0];y[0] = t;
681 }
682}
683
684//do x=x**(-1) mod n, for bigInts x and n.
685//If no inverse exists, it sets x to zero and returns 0, else it returns 1.
686//The x array must be at least as large as the n array.
687function inverseMod_(x, n) {
688 var k = 1 + 2 * Math.max(x.length, n.length);
689
690 if (!(x[0] & 1) && !(n[0] & 1)) {
691 //if both inputs are even, then inverse doesn't exist
692 copyInt_(x, 0);
693 return 0;
694 }
695
696 if (eg_u.length != k) {
697 eg_u = new Array(k);
698 eg_v = new Array(k);
699 eg_A = new Array(k);
700 eg_B = new Array(k);
701 eg_C = new Array(k);
702 eg_D = new Array(k);
703 }
704
705 copy_(eg_u, x);
706 copy_(eg_v, n);
707 copyInt_(eg_A, 1);
708 copyInt_(eg_B, 0);
709 copyInt_(eg_C, 0);
710 copyInt_(eg_D, 1);
711 for (;;) {
712 while (!(eg_u[0] & 1)) {
713 //while eg_u is even
714 halve_(eg_u);
715 if (!(eg_A[0] & 1) && !(eg_B[0] & 1)) {
716 //if eg_A==eg_B==0 mod 2
717 halve_(eg_A);
718 halve_(eg_B);
719 } else {
720 add_(eg_A, n);halve_(eg_A);
721 sub_(eg_B, x);halve_(eg_B);
722 }
723 }
724
725 while (!(eg_v[0] & 1)) {
726 //while eg_v is even
727 halve_(eg_v);
728 if (!(eg_C[0] & 1) && !(eg_D[0] & 1)) {
729 //if eg_C==eg_D==0 mod 2
730 halve_(eg_C);
731 halve_(eg_D);
732 } else {
733 add_(eg_C, n);halve_(eg_C);
734 sub_(eg_D, x);halve_(eg_D);
735 }
736 }
737
738 if (!greater(eg_v, eg_u)) {
739 //eg_v <= eg_u
740 sub_(eg_u, eg_v);
741 sub_(eg_A, eg_C);
742 sub_(eg_B, eg_D);
743 } else {
744 //eg_v > eg_u
745 sub_(eg_v, eg_u);
746 sub_(eg_C, eg_A);
747 sub_(eg_D, eg_B);
748 }
749
750 if (equalsInt(eg_u, 0)) {
751 while (negative(eg_C)) //make sure answer is nonnegative
752 add_(eg_C, n);
753 copy_(x, eg_C);
754
755 if (!equalsInt(eg_v, 1)) {
756 //if GCD_(x,n)!=1, then there is no inverse
757 copyInt_(x, 0);
758 return 0;
759 }
760 return 1;
761 }
762 }
763}
764
765//return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
766function inverseModInt(x, n) {
767 var a = 1,
768 b = 0,
769 t;
770 for (;;) {
771 if (x == 1) return a;
772 if (x == 0) return 0;
773 b -= a * Math.floor(n / x);
774 n %= x;
775
776 if (n == 1) return b; //to avoid negatives, change this b to n-b, and each -= to +=
777 if (n == 0) return 0;
778 a -= b * Math.floor(x / n);
779 x %= n;
780 }
781}
782
783//this deprecated function is for backward compatibility only.
784function inverseModInt_(x, n) {
785 return inverseModInt(x, n);
786}
787
788//Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that:
789// v = GCD_(x,y) = a*x-b*y
790//The bigInts v, a, b, must have exactly as many elements as the larger of x and y.
791export function eGCD_(x, y, v, a, b) {
792 var g = 0;
793 var k = Math.max(x.length, y.length);
794 if (eg_u.length != k) {
795 eg_u = new Array(k);
796 eg_A = new Array(k);
797 eg_B = new Array(k);
798 eg_C = new Array(k);
799 eg_D = new Array(k);
800 }
801 while (!(x[0] & 1) && !(y[0] & 1)) {
802 //while x and y both even
803 halve_(x);
804 halve_(y);
805 g++;
806 }
807 copy_(eg_u, x);
808 copy_(v, y);
809 copyInt_(eg_A, 1);
810 copyInt_(eg_B, 0);
811 copyInt_(eg_C, 0);
812 copyInt_(eg_D, 1);
813 for (;;) {
814 while (!(eg_u[0] & 1)) {
815 //while u is even
816 halve_(eg_u);
817 if (!(eg_A[0] & 1) && !(eg_B[0] & 1)) {
818 //if A==B==0 mod 2
819 halve_(eg_A);
820 halve_(eg_B);
821 } else {
822 add_(eg_A, y);halve_(eg_A);
823 sub_(eg_B, x);halve_(eg_B);
824 }
825 }
826
827 while (!(v[0] & 1)) {
828 //while v is even
829 halve_(v);
830 if (!(eg_C[0] & 1) && !(eg_D[0] & 1)) {
831 //if C==D==0 mod 2
832 halve_(eg_C);
833 halve_(eg_D);
834 } else {
835 add_(eg_C, y);halve_(eg_C);
836 sub_(eg_D, x);halve_(eg_D);
837 }
838 }
839
840 if (!greater(v, eg_u)) {
841 //v<=u
842 sub_(eg_u, v);
843 sub_(eg_A, eg_C);
844 sub_(eg_B, eg_D);
845 } else {
846 //v>u
847 sub_(v, eg_u);
848 sub_(eg_C, eg_A);
849 sub_(eg_D, eg_B);
850 }
851 if (equalsInt(eg_u, 0)) {
852 while (negative(eg_C)) {
853 //make sure a (C) is nonnegative
854 add_(eg_C, y);
855 sub_(eg_D, x);
856 }
857 multInt_(eg_D, -1); ///make sure b (D) is nonnegative
858 copy_(a, eg_C);
859 copy_(b, eg_D);
860 leftShift_(v, g);
861 return;
862 }
863 }
864}
865
866//is bigInt x negative?
867function negative(x) {
868 return x[x.length - 1] >> bpe - 1 & 1;
869}
870
871//is (x << (shift*bpe)) > y?
872//x and y are nonnegative bigInts
873//shift is a nonnegative integer
874function greaterShift(x, y, shift) {
875 var i,
876 kx = x.length,
877 ky = y.length;
878 k = kx + shift < ky ? kx + shift : ky;
879 for (i = ky - 1 - shift; i < kx && i >= 0; i++) if (x[i] > 0) return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger
880 for (i = kx - 1 + shift; i < ky; i++) if (y[i] > 0) return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger
881 for (i = k - 1; i >= shift; i--) if (x[i - shift] > y[i]) return 1;else if (x[i - shift] < y[i]) return 0;
882 return 0;
883}
884
885//is x > y? (x and y both nonnegative)
886export function greater(x, y) {
887 var i;
888 var k = x.length < y.length ? x.length : y.length;
889
890 for (i = x.length; i < y.length; i++) if (y[i]) return 0; //y has more digits
891
892 for (i = y.length; i < x.length; i++) if (x[i]) return 1; //x has more digits
893
894 for (i = k - 1; i >= 0; i--) if (x[i] > y[i]) return 1;else if (x[i] < y[i]) return 0;
895 return 0;
896}
897
898//divide x by y giving quotient q and remainder r. (q=floor(x/y), r=x mod y). All 4 are bigints.
899//x must have at least one leading zero element.
900//y must be nonzero.
901//q and r must be arrays that are exactly the same length as x. (Or q can have more).
902//Must have x.length >= y.length >= 2.
903export function divide_(x, y, q, r) {
904 var kx, ky;
905 var i, j, y1, y2, c, a, b;
906 copy_(r, x);
907 for (ky = y.length; y[ky - 1] == 0; ky--); //ky is number of elements in y, not including leading zeros
908
909 //normalize: ensure the most significant element of y has its highest bit set
910 b = y[ky - 1];
911 for (a = 0; b; a++) b >>= 1;
912 a = bpe - a; //a is how many bits to shift so that the high order bit of y is leftmost in its array element
913 leftShift_(y, a); //multiply both by 1<<a now, then divide both by that at the end
914 leftShift_(r, a);
915
916 //Rob Visser discovered a bug: the following line was originally just before the normalization.
917 for (kx = r.length; r[kx - 1] == 0 && kx > ky; kx--); //kx is number of elements in normalized x, not including leading zeros
918
919 copyInt_(q, 0); // q=0
920 while (!greaterShift(y, r, kx - ky)) {
921 // while (leftShift_(y,kx-ky) <= r) {
922 subShift_(r, y, kx - ky); // r=r-leftShift_(y,kx-ky)
923 q[kx - ky]++; // q[kx-ky]++;
924 } // }
925
926 for (i = kx - 1; i >= ky; i--) {
927 if (r[i] == y[ky - 1]) q[i - ky] = mask;else q[i - ky] = Math.floor((r[i] * radix + r[i - 1]) / y[ky - 1]);
928
929 //The following for(;;) loop is equivalent to the commented while loop,
930 //except that the uncommented version avoids overflow.
931 //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0
932 // while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2])
933 // q[i-ky]--;
934 for (;;) {
935 y2 = (ky > 1 ? y[ky - 2] : 0) * q[i - ky];
936 c = y2 >> bpe;
937 y2 = y2 & mask;
938 y1 = c + q[i - ky] * y[ky - 1];
939 c = y1 >> bpe;
940 y1 = y1 & mask;
941
942 if (c == r[i] ? y1 == r[i - 1] ? y2 > (i > 1 ? r[i - 2] : 0) : y1 > r[i - 1] : c > r[i]) q[i - ky]--;else break;
943 }
944
945 linCombShift_(r, y, -q[i - ky], i - ky); //r=r-q[i-ky]*leftShift_(y,i-ky)
946 if (negative(r)) {
947 addShift_(r, y, i - ky); //r=r+leftShift_(y,i-ky)
948 q[i - ky]--;
949 }
950 }
951
952 rightShift_(y, a); //undo the normalization step
953 rightShift_(r, a); //undo the normalization step
954}
955
956//do carries and borrows so each element of the bigInt x fits in bpe bits.
957function carry_(x) {
958 var i, k, c, b;
959 k = x.length;
960 c = 0;
961 for (i = 0; i < k; i++) {
962 c += x[i];
963 b = 0;
964 if (c < 0) {
965 b = -(c >> bpe);
966 c += b * radix;
967 }
968 x[i] = c & mask;
969 c = (c >> bpe) - b;
970 }
971}
972
973//return x mod n for bigInt x and integer n.
974function modInt(x, n) {
975 var i,
976 c = 0;
977 for (i = x.length - 1; i >= 0; i--) c = (c * radix + x[i]) % n;
978 return c;
979}
980
981//convert the integer t into a bigInt with at least the given number of bits.
982//the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word)
983//Pad the array with leading zeros so that it has at least minSize elements.
984//There will always be at least one leading 0 element.
985function int2bigInt(t, bits, minSize) {
986 var i, k;
987 k = Math.ceil(bits / bpe) + 1;
988 k = minSize > k ? minSize : k;
989 var buff = new Array(k);
990 copyInt_(buff, t);
991 return buff;
992}
993
994//return the bigInt given a string representation in a given base.
995//Pad the array with leading zeros so that it has at least minSize elements.
996//If base=-1, then it reads in a space-separated list of array elements in decimal.
997//The array will always have at least one leading zero, unless base=-1.
998export function str2bigInt(s, base, minSize) {
999 var d, i, j, x, y, kk;
1000 var k = s.length;
1001 if (base == -1) {
1002 //comma-separated list of array elements in decimal
1003 x = new Array(0);
1004 for (;;) {
1005 y = new Array(x.length + 1);
1006 for (i = 0; i < x.length; i++) y[i + 1] = x[i];
1007 y[0] = parseInt(s, 10);
1008 x = y;
1009 d = s.indexOf(',', 0);
1010 if (d < 1) break;
1011 s = s.substring(d + 1);
1012 if (s.length == 0) break;
1013 }
1014 if (x.length < minSize) {
1015 y = new Array(minSize);
1016 copy_(y, x);
1017 return y;
1018 }
1019 return x;
1020 }
1021
1022 x = int2bigInt(0, base * k, 0);
1023 for (i = 0; i < k; i++) {
1024 d = digitsStr.indexOf(s.substring(i, i + 1), 0);
1025 if (base <= 36 && d >= 36) //convert lowercase to uppercase if base<=36
1026 d -= 26;
1027 if (d >= base || d < 0) {
1028 //stop at first illegal character
1029 break;
1030 }
1031 multInt_(x, base);
1032 addInt_(x, d);
1033 }
1034
1035 for (k = x.length; k > 0 && !x[k - 1]; k--); //strip off leading zeros
1036 k = minSize > k + 1 ? minSize : k + 1;
1037 y = new Array(k);
1038 kk = k < x.length ? k : x.length;
1039 for (i = 0; i < kk; i++) y[i] = x[i];
1040 for (; i < k; i++) y[i] = 0;
1041 return y;
1042}
1043
1044//is bigint x equal to integer y?
1045//y must have less than bpe bits
1046export function equalsInt(x, y) {
1047 var i;
1048 if (x[0] != y) return 0;
1049 for (i = 1; i < x.length; i++) if (x[i]) return 0;
1050 return 1;
1051}
1052
1053//are bigints x and y equal?
1054//this works even if x and y are different lengths and have arbitrarily many leading zeros
1055function equals(x, y) {
1056 var i;
1057 var k = x.length < y.length ? x.length : y.length;
1058 for (i = 0; i < k; i++) if (x[i] != y[i]) return 0;
1059 if (x.length > y.length) {
1060 for (; i < x.length; i++) if (x[i]) return 0;
1061 } else {
1062 for (; i < y.length; i++) if (y[i]) return 0;
1063 }
1064 return 1;
1065}
1066
1067//is the bigInt x equal to zero?
1068export function isZero(x) {
1069 var i;
1070 for (i = 0; i < x.length; i++) if (x[i]) return 0;
1071 return 1;
1072}
1073
1074//convert a bigInt into a string in a given base, from base 2 up to base 95.
1075//Base -1 prints the contents of the array representing the number.
1076export function bigInt2str(x, base) {
1077 var i,
1078 t,
1079 s = "";
1080
1081 if (s6.length != x.length) s6 = dup(x);else copy_(s6, x);
1082
1083 if (base == -1) {
1084 //return the list of array contents
1085 for (i = x.length - 1; i > 0; i--) s += x[i] + ',';
1086 s += x[0];
1087 } else {
1088 //return it in the given base
1089 while (!isZero(s6)) {
1090 t = divInt_(s6, base); //t=s6 % base; s6=floor(s6/base);
1091 s = digitsStr.substring(t, t + 1) + s;
1092 }
1093 }
1094 if (s.length == 0) s = "0";
1095 return s;
1096}
1097
1098//returns a duplicate of bigInt x
1099function dup(x) {
1100 var i;
1101 buff = new Array(x.length);
1102 copy_(buff, x);
1103 return buff;
1104}
1105
1106//do x=y on bigInts x and y. x must be an array at least as big as y (not counting the leading zeros in y).
1107export function copy_(x, y) {
1108 var i;
1109 var k = x.length < y.length ? x.length : y.length;
1110 for (i = 0; i < k; i++) x[i] = y[i];
1111 for (i = k; i < x.length; i++) x[i] = 0;
1112}
1113
1114//do x=y on bigInt x and integer y.
1115export function copyInt_(x, n) {
1116 var i, c;
1117 for (c = n, i = 0; i < x.length; i++) {
1118 x[i] = c & mask;
1119 c >>= bpe;
1120 }
1121}
1122
1123//do x=x+n where x is a bigInt and n is an integer.
1124//x must be large enough to hold the result.
1125function addInt_(x, n) {
1126 var i, k, c, b;
1127 x[0] += n;
1128 k = x.length;
1129 c = 0;
1130 for (i = 0; i < k; i++) {
1131 c += x[i];
1132 b = 0;
1133 if (c < 0) {
1134 b = -(c >> bpe);
1135 c += b * radix;
1136 }
1137 x[i] = c & mask;
1138 c = (c >> bpe) - b;
1139 if (!c) return; //stop carrying as soon as the carry is zero
1140 }
1141}
1142
1143//right shift bigInt x by n bits. 0 <= n < bpe.
1144export function rightShift_(x, n) {
1145 var i;
1146 var k = Math.floor(n / bpe);
1147 if (k) {
1148 for (i = 0; i < x.length - k; i++) //right shift x by k elements
1149 x[i] = x[i + k];
1150 for (; i < x.length; i++) x[i] = 0;
1151 n %= bpe;
1152 }
1153 for (i = 0; i < x.length - 1; i++) {
1154 x[i] = mask & (x[i + 1] << bpe - n | x[i] >> n);
1155 }
1156 x[i] >>= n;
1157}
1158
1159//do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
1160function halve_(x) {
1161 var i;
1162 for (i = 0; i < x.length - 1; i++) {
1163 x[i] = mask & (x[i + 1] << bpe - 1 | x[i] >> 1);
1164 }
1165 x[i] = x[i] >> 1 | x[i] & radix >> 1; //most significant bit stays the same
1166}
1167
1168//left shift bigInt x by n bits.
1169function leftShift_(x, n) {
1170 var i;
1171 var k = Math.floor(n / bpe);
1172 if (k) {
1173 for (i = x.length; i >= k; i--) //left shift x by k elements
1174 x[i] = x[i - k];
1175 for (; i >= 0; i--) x[i] = 0;
1176 n %= bpe;
1177 }
1178 if (!n) return;
1179 for (i = x.length - 1; i > 0; i--) {
1180 x[i] = mask & (x[i] << n | x[i - 1] >> bpe - n);
1181 }
1182 x[i] = mask & x[i] << n;
1183}
1184
1185//do x=x*n where x is a bigInt and n is an integer.
1186//x must be large enough to hold the result.
1187function multInt_(x, n) {
1188 var i, k, c, b;
1189 if (!n) return;
1190 k = x.length;
1191 c = 0;
1192 for (i = 0; i < k; i++) {
1193 c += x[i] * n;
1194 b = 0;
1195 if (c < 0) {
1196 b = -(c >> bpe);
1197 c += b * radix;
1198 }
1199 x[i] = c & mask;
1200 c = (c >> bpe) - b;
1201 }
1202}
1203
1204//do x=floor(x/n) for bigInt x and integer n, and return the remainder
1205function divInt_(x, n) {
1206 var i,
1207 r = 0,
1208 s;
1209 for (i = x.length - 1; i >= 0; i--) {
1210 s = r * radix + x[i];
1211 x[i] = Math.floor(s / n);
1212 r = s % n;
1213 }
1214 return r;
1215}
1216
1217//do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b.
1218//x must be large enough to hold the answer.
1219function linComb_(x, y, a, b) {
1220 var i, c, k, kk;
1221 k = x.length < y.length ? x.length : y.length;
1222 kk = x.length;
1223 for (c = 0, i = 0; i < k; i++) {
1224 c += a * x[i] + b * y[i];
1225 x[i] = c & mask;
1226 c >>= bpe;
1227 }
1228 for (i = k; i < kk; i++) {
1229 c += a * x[i];
1230 x[i] = c & mask;
1231 c >>= bpe;
1232 }
1233}
1234
1235//do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys.
1236//x must be large enough to hold the answer.
1237function linCombShift_(x, y, b, ys) {
1238 var i, c, k, kk;
1239 k = x.length < ys + y.length ? x.length : ys + y.length;
1240 kk = x.length;
1241 for (c = 0, i = ys; i < k; i++) {
1242 c += x[i] + b * y[i - ys];
1243 x[i] = c & mask;
1244 c >>= bpe;
1245 }
1246 for (i = k; c && i < kk; i++) {
1247 c += x[i];
1248 x[i] = c & mask;
1249 c >>= bpe;
1250 }
1251}
1252
1253//do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
1254//x must be large enough to hold the answer.
1255function addShift_(x, y, ys) {
1256 var i, c, k, kk;
1257 k = x.length < ys + y.length ? x.length : ys + y.length;
1258 kk = x.length;
1259 for (c = 0, i = ys; i < k; i++) {
1260 c += x[i] + y[i - ys];
1261 x[i] = c & mask;
1262 c >>= bpe;
1263 }
1264 for (i = k; c && i < kk; i++) {
1265 c += x[i];
1266 x[i] = c & mask;
1267 c >>= bpe;
1268 }
1269}
1270
1271//do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
1272//x must be large enough to hold the answer.
1273function subShift_(x, y, ys) {
1274 var i, c, k, kk;
1275 k = x.length < ys + y.length ? x.length : ys + y.length;
1276 kk = x.length;
1277 for (c = 0, i = ys; i < k; i++) {
1278 c += x[i] - y[i - ys];
1279 x[i] = c & mask;
1280 c >>= bpe;
1281 }
1282 for (i = k; c && i < kk; i++) {
1283 c += x[i];
1284 x[i] = c & mask;
1285 c >>= bpe;
1286 }
1287}
1288
1289//do x=x-y for bigInts x and y.
1290//x must be large enough to hold the answer.
1291//negative answers will be 2s complement
1292export function sub_(x, y) {
1293 var i, c, k, kk;
1294 k = x.length < y.length ? x.length : y.length;
1295 for (c = 0, i = 0; i < k; i++) {
1296 c += x[i] - y[i];
1297 x[i] = c & mask;
1298 c >>= bpe;
1299 }
1300 for (i = k; c && i < x.length; i++) {
1301 c += x[i];
1302 x[i] = c & mask;
1303 c >>= bpe;
1304 }
1305}
1306
1307//do x=x+y for bigInts x and y.
1308//x must be large enough to hold the answer.
1309export function add_(x, y) {
1310 var i, c, k, kk;
1311 k = x.length < y.length ? x.length : y.length;
1312 for (c = 0, i = 0; i < k; i++) {
1313 c += x[i] + y[i];
1314 x[i] = c & mask;
1315 c >>= bpe;
1316 }
1317 for (i = k; c && i < x.length; i++) {
1318 c += x[i];
1319 x[i] = c & mask;
1320 c >>= bpe;
1321 }
1322}
1323
1324//do x=x*y for bigInts x and y. This is faster when y<x.
1325function mult_(x, y) {
1326 var i;
1327 if (ss.length != 2 * x.length) ss = new Array(2 * x.length);
1328 copyInt_(ss, 0);
1329 for (i = 0; i < y.length; i++) if (y[i]) linCombShift_(ss, x, y[i], i); //ss=1*ss+y[i]*(x<<(i*bpe))
1330 copy_(x, ss);
1331}
1332
1333//do x=x mod n for bigInts x and n.
1334function mod_(x, n) {
1335 if (s4.length != x.length) s4 = dup(x);else copy_(s4, x);
1336 if (s5.length != x.length) s5 = dup(x);
1337 divide_(s4, n, s5, x); //x = remainder of s4 / n
1338}
1339
1340//do x=x*y mod n for bigInts x,y,n.
1341//for greater speed, let y<x.
1342function multMod_(x, y, n) {
1343 var i;
1344 if (s0.length != 2 * x.length) s0 = new Array(2 * x.length);
1345 copyInt_(s0, 0);
1346 for (i = 0; i < y.length; i++) if (y[i]) linCombShift_(s0, x, y[i], i); //s0=1*s0+y[i]*(x<<(i*bpe))
1347 mod_(s0, n);
1348 copy_(x, s0);
1349}
1350
1351//do x=x*x mod n for bigInts x,n.
1352function squareMod_(x, n) {
1353 var i, j, d, c, kx, kn, k;
1354 for (kx = x.length; kx > 0 && !x[kx - 1]; kx--); //ignore leading zeros in x
1355 k = kx > n.length ? 2 * kx : 2 * n.length; //k=# elements in the product, which is twice the elements in the larger of x and n
1356 if (s0.length != k) s0 = new Array(k);
1357 copyInt_(s0, 0);
1358 for (i = 0; i < kx; i++) {
1359 c = s0[2 * i] + x[i] * x[i];
1360 s0[2 * i] = c & mask;
1361 c >>= bpe;
1362 for (j = i + 1; j < kx; j++) {
1363 c = s0[i + j] + 2 * x[i] * x[j] + c;
1364 s0[i + j] = c & mask;
1365 c >>= bpe;
1366 }
1367 s0[i + kx] = c;
1368 }
1369 mod_(s0, n);
1370 copy_(x, s0);
1371}
1372
1373//return x with exactly k leading zero elements
1374function trim(x, k) {
1375 var i, y;
1376 for (i = x.length; i > 0 && !x[i - 1]; i--);
1377 y = new Array(i + k);
1378 copy_(y, x);
1379 return y;
1380}
1381
1382//do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation. 0**0=1.
1383//this is faster when n is odd. x usually needs to have as many elements as n.
1384function powMod_(x, y, n) {
1385 var k1, k2, kn, np;
1386 if (s7.length != n.length) s7 = dup(n);
1387
1388 //for even modulus, use a simple square-and-multiply algorithm,
1389 //rather than using the more complex Montgomery algorithm.
1390 if ((n[0] & 1) == 0) {
1391 copy_(s7, x);
1392 copyInt_(x, 1);
1393 while (!equalsInt(y, 0)) {
1394 if (y[0] & 1) multMod_(x, s7, n);
1395 divInt_(y, 2);
1396 squareMod_(s7, n);
1397 }
1398 return;
1399 }
1400
1401 //calculate np from n for the Montgomery multiplications
1402 copyInt_(s7, 0);
1403 for (kn = n.length; kn > 0 && !n[kn - 1]; kn--);
1404 np = radix - inverseModInt(modInt(n, radix), radix);
1405 s7[kn] = 1;
1406 multMod_(x, s7, n); // x = x * 2**(kn*bp) mod n
1407
1408 if (s3.length != x.length) s3 = dup(x);else copy_(s3, x);
1409
1410 for (k1 = y.length - 1; k1 > 0 & !y[k1]; k1--); //k1=first nonzero element of y
1411 if (y[k1] == 0) {
1412 //anything to the 0th power is 1
1413 copyInt_(x, 1);
1414 return;
1415 }
1416 for (k2 = 1 << bpe - 1; k2 && !(y[k1] & k2); k2 >>= 1); //k2=position of first 1 bit in y[k1]
1417 for (;;) {
1418 if (!(k2 >>= 1)) {
1419 //look at next bit of y
1420 k1--;
1421 if (k1 < 0) {
1422 mont_(x, one, n, np);
1423 return;
1424 }
1425 k2 = 1 << bpe - 1;
1426 }
1427 mont_(x, x, n, np);
1428
1429 if (k2 & y[k1]) //if next bit is a 1
1430 mont_(x, s3, n, np);
1431 }
1432}
1433
1434//do x=x*y*Ri mod n for bigInts x,y,n,
1435// where Ri = 2**(-kn*bpe) mod n, and kn is the
1436// number of elements in the n array, not
1437// counting leading zeros.
1438//x array must have at least as many elemnts as the n array
1439//It's OK if x and y are the same variable.
1440//must have:
1441// x,y < n
1442// n is odd
1443// np = -(n^(-1)) mod radix
1444function mont_(x, y, n, np) {
1445 var i, j, c, ui, t, ks;
1446 var kn = n.length;
1447 var ky = y.length;
1448
1449 if (sa.length != kn) sa = new Array(kn);
1450
1451 copyInt_(sa, 0);
1452
1453 for (; kn > 0 && n[kn - 1] == 0; kn--); //ignore leading zeros of n
1454 for (; ky > 0 && y[ky - 1] == 0; ky--); //ignore leading zeros of y
1455 ks = sa.length - 1; //sa will never have more than this many nonzero elements.
1456
1457 //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers
1458 for (i = 0; i < kn; i++) {
1459 t = sa[0] + x[i] * y[0];
1460 ui = (t & mask) * np & mask; //the inner "& mask" was needed on Safari (but not MSIE) at one time
1461 c = t + ui * n[0] >> bpe;
1462 t = x[i];
1463
1464 //do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe. Loop is unrolled 5-fold for speed
1465 j = 1;
1466 for (; j < ky - 4;) {
1467 c += sa[j] + ui * n[j] + t * y[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1468 c += sa[j] + ui * n[j] + t * y[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1469 c += sa[j] + ui * n[j] + t * y[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1470 c += sa[j] + ui * n[j] + t * y[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1471 c += sa[j] + ui * n[j] + t * y[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1472 }
1473 for (; j < ky;) {
1474 c += sa[j] + ui * n[j] + t * y[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1475 }
1476 for (; j < kn - 4;) {
1477 c += sa[j] + ui * n[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1478 c += sa[j] + ui * n[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1479 c += sa[j] + ui * n[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1480 c += sa[j] + ui * n[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1481 c += sa[j] + ui * n[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1482 }
1483 for (; j < kn;) {
1484 c += sa[j] + ui * n[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1485 }
1486 for (; j < ks;) {
1487 c += sa[j];sa[j - 1] = c & mask;c >>= bpe;j++;
1488 }
1489 sa[j - 1] = c & mask;
1490 }
1491
1492 if (!greater(n, sa)) sub_(sa, n);
1493 copy_(x, sa);
1494}
1495//# sourceMappingURL=leemon.js.map
\No newline at end of file