UNPKG

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