source: trunk/phpgwapi/js/expressoAjax/bigInt.js @ 2931

Revision 2931, 26.9 KB checked in by amuller, 14 years ago (diff)

Ticket #1036 - Adicionando ponto e vírgula faltante e mudando nomes

Line 
1////////////////////////////////////////////////////////////////////////////////////////
2// Big Integer Library v. 5.4
3// Created 2000, last modified 2009
4// Leemon Baird
5// www.leemon.com
6//
7// Version history:
8// v 5.4  3 Oct 2009
9//   - added "var i" to greaterShift() so i is not global. (Thanks to Pr Szabor finding that bug)
10//
11// v 5.3  21 Sep 2009
12//   - added randProbPrime(k) for probable primes
13//   - unrolled loop in mont_ (slightly faster)
14//   - millerRabin now takes a bigInt parameter rather than an int
15//
16// v 5.2  15 Sep 2009
17//   - fixed capitalization in call to int2bigInt in randBigInt
18//     (thanks to Emili Evripidou, Reinhold Behringer, and Samuel Macaleese for finding that bug)
19//
20// v 5.1  8 Oct 2007
21//   - renamed inverseModInt_ to inverseModInt since it doesn't change its parameters
22//   - added functions GCD and randBigInt, which call GCD_ and randBigInt_
23//   - fixed a bug found by Rob Visser (see comment with his name below)
24//   - improved comments
25//
26// This file is public domain.   You can use it for any purpose without restriction.
27// I do not guarantee that it is correct, so use it at your own risk.  If you use
28// it for something interesting, I'd appreciate hearing about it.  If you find
29// any bugs or make any improvements, I'd appreciate hearing about those too.
30// It would also be nice if my name and URL were left in the comments.  But none
31// of that is required.
32//
33// This code defines a bigInt library for arbitrary-precision integers.
34// A bigInt is an array of integers storing the value in chunks of bpe bits,
35// little endian (buff[0] is the least significant word).
36// Negative bigInts are stored two's complement.  Almost all the functions treat
37// bigInts as nonnegative.  The few that view them as two's complement say so
38// in their comments.  Some functions assume their parameters have at least one
39// leading zero element. Functions with an underscore at the end of the name put
40// their answer into one of the arrays passed in, and have unpredictable behavior
41// in case of overflow, so the caller must make sure the arrays are big enough to
42// hold the answer.  But the average user should never have to call any of the
43// underscored functions.  Each important underscored function has a wrapper function
44// of the same name without the underscore that takes care of the details for you. 
45// For each underscored function where a parameter is modified, that same variable
46// must not be used as another argument too.  So, you cannot square x by doing
47// multMod_(x,x,n).  You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n).
48// Or simply use the multMod(x,x,n) function without the underscore, where
49// such issues never arise, because non-underscored functions never change
50// their parameters; they always allocate new memory for the answer that is returned.
51//
52// These functions are designed to avoid frequent dynamic memory allocation in the inner loop.
53// For most functions, if it needs a BigInt as a local variable it will actually use
54// a global, and will only allocate to it only when it's not the right size.  This ensures
55// that when a function is called repeatedly with same-sized parameters, it only allocates
56// memory on the first call.
57//
58// Note that for cryptographic purposes, the calls to Math.random() must
59// be replaced with calls to a better pseudorandom number generator.
60//
61// In the following, "bigInt" means a bigInt with at least one leading zero element,
62// and "integer" means a nonnegative integer less than radix.  In some cases, integer
63// can be negative.  Negative bigInts are 2s complement.
64//
65// The following functions do not modify their inputs.
66// Those returning a bigInt, string, or Array will dynamically allocate memory for that value.
67// Those returning a boolean will return the integer 0 (false) or 1 (true).
68// Those returning boolean or int will not allocate memory except possibly on the first
69// time they're called with a given parameter size.
70
71
72//globals
73bpe=0;         //bits stored per array element
74mask=0;        //AND this with an array element to chop it down to bpe bits
75radix=mask+1;  //equals 2^bpe.  A single 1 bit to the left of the last bit of mask.
76
77//the digits for converting to different bases
78digitsStr='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\\'\"+-';
79
80//initialize the global variables
81for (bpe=0; (1<<(bpe+1)) > (1<<bpe); bpe++);  //bpe=number of bits in the mantissa on this platform
82bpe>>=1;                   //bpe=number of bits in one element of the array representing the bigInt
83mask=(1<<bpe)-1;           //AND the mask with an integer to get its bpe least significant bits
84radix=mask+1;              //2^bpe.  a single 1 bit to the left of the first bit of mask
85one=int2bigInt(1,1,1);     //constant used in powMod_()
86
87//the following global variables are scratchpad memory to
88//reduce dynamic memory allocation in the inner loop
89t=new Array(0);
90ss=t;       //used in mult_()
91s0=t;       //used in multMod_(), squareMod_()
92s1=t;       //used in powMod_(), multMod_(), squareMod_()
93s2=t;       //used in powMod_(), multMod_()
94s3=t;       //used in powMod_()
95s4=t; s5=t; //used in mod_()
96s6=t;       //used in bigInt2str()
97s7=t;       //used in powMod_()
98T=t;        //used in GCD_()
99sa=t;       //used in mont_()
100mr_x1=t; mr_r=t; mr_a=t;                                      //used in millerRabin()
101eg_v=t; eg_u=t; eg_A=t; eg_B=t; eg_C=t; eg_D=t;               //used in eGCD_(), inverseMod_()
102md_q1=t; md_q2=t; md_q3=t; md_r=t; md_r1=t; md_r2=t; md_tt=t; //used in mod_()
103
104primes=t; pows=t; s_i=t; s_i2=t; s_R=t; s_rm=t; s_q=t; s_n1=t;
105  s_a=t; s_r2=t; s_n=t; s_b=t; s_d=t; s_x1=t; s_x2=t, s_aa=t; //used in randTruePrime_()
106 
107rpprb=t; //used in randProbPrimeRounds() (which also uses "primes")
108
109//return a copy of x with at least n elements, adding leading zeros if needed
110function expand(x,n) {
111  var ans=int2bigInt(0,(x.length>n ? x.length : n)*bpe,0);
112  copy_(ans,x);
113  return ans;
114}
115//return (x**y mod n) where x,y,n are bigInts and ** is exponentiation.  0**0=1. Faster for odd n.
116function powMod(x,y,n) {
117  var ans=expand(x,n.length); 
118  powMod_(ans,bigintTrim(y,2),bigintTrim(n,2),0);  //this should work without the bigintTrim, but doesn't
119  return bigintTrim(ans,1);
120}
121
122//return (x-y) for bigInts x and y.  Negative answers will be 2s complement
123function sub(x,y) {
124  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
125  sub_(ans,y);
126  return bigintTrim(ans,1);
127}
128
129//return (x+y) for bigInts x and y. 
130function add(x,y) {
131  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
132  add_(ans,y);
133  return bigintTrim(ans,1);
134}
135//Return the greatest common divisor of bigInts x and y (each with same number of elements).
136function GCD(x,y) {
137  var xc,yc;
138  xc=dup(x);
139  yc=dup(y);
140  GCD_(xc,yc);
141  return xc;
142}
143
144//set x to the greatest common divisor of bigInts x and y (each with same number of elements).
145//y is destroyed.
146function GCD_(x,y) {
147  var i,xp,yp,A,B,C,D,q,sing;
148  if (T.length!=x.length)
149    T=dup(x);
150
151  sing=1;
152  while (sing) { //while y has nonzero elements other than y[0]
153    sing=0;
154    for (i=1;i<y.length;i++) //check if y has nonzero elements other than 0
155      if (y[i]) {
156        sing=1;
157        break;
158      }
159    if (!sing) break; //quit when y all zero elements except possibly y[0]
160
161    for (i=x.length;!x[i] && i>=0;i--);  //find most significant element of x
162    xp=x[i];
163    yp=y[i];
164    A=1; B=0; C=0; D=1;
165    while ((yp+C) && (yp+D)) {
166      q =Math.floor((xp+A)/(yp+C));
167      qp=Math.floor((xp+B)/(yp+D));
168      if (q!=qp)
169        break;
170      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)     
171      t= B-q*D;   B=D;   D=t;
172      t=xp-q*yp; xp=yp; yp=t;
173    }
174    if (B) {
175      copy_(T,x);
176      linComb_(x,y,A,B); //x=A*x+B*y
177      linComb_(y,T,D,C); //y=D*y+C*T
178    } else {
179      mod_(x,y);
180      copy_(T,x);
181      copy_(x,y);
182      copy_(y,T);
183    }
184  }
185  if (y[0]==0)
186    return;
187  t=modInt(x,y[0]);
188  copyInt_(x,y[0]);
189  y[0]=t;
190  while (y[0]) {
191    x[0]%=y[0];
192    t=x[0]; x[0]=y[0]; y[0]=t;
193  }
194}
195
196//return x**(-1) mod n, for integers x and n.  Return 0 if there is no inverse
197function inverseModInt(x,n) {
198  var a=1,b=0,t;
199  for (;;) {
200    if (x==1) return a;
201    if (x==0) return 0;
202    b-=a*Math.floor(n/x);
203    n%=x;
204
205    if (n==1) return b; //to avoid negatives, change this b to n-b, and each -= to +=
206    if (n==0) return 0;
207    a-=b*Math.floor(x/n);
208    x%=n;
209  }
210}
211
212//this deprecated function is for backward compatibility only.
213function inverseModInt_(x,n) {
214   return inverseModInt(x,n);
215}
216
217
218//Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that:
219//     v = GCD_(x,y) = a*x-b*y
220//The bigInts v, a, b, must have exactly as many elements as the larger of x and y.
221function eGCD_(x,y,v,a,b) {
222  var g=0;
223  var k=Math.max(x.length,y.length);
224  if (eg_u.length!=k) {
225    eg_u=new Array(k);
226    eg_A=new Array(k);
227    eg_B=new Array(k);
228    eg_C=new Array(k);
229    eg_D=new Array(k);
230  }
231  while(!(x[0]&1)  && !(y[0]&1)) {  //while x and y both even
232    halve_(x);
233    halve_(y);
234    g++;
235  }
236  copy_(eg_u,x);
237  copy_(v,y);
238  copyInt_(eg_A,1);
239  copyInt_(eg_B,0);
240  copyInt_(eg_C,0);
241  copyInt_(eg_D,1);
242  for (;;) {
243    while(!(eg_u[0]&1)) {  //while u is even
244      halve_(eg_u);
245      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if A==B==0 mod 2
246        halve_(eg_A);
247        halve_(eg_B);     
248      } else {
249        add_(eg_A,y);  halve_(eg_A);
250        sub_(eg_B,x);  halve_(eg_B);
251      }
252    }
253
254    while (!(v[0]&1)) {  //while v is even
255      halve_(v);
256      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if C==D==0 mod 2
257        halve_(eg_C);
258        halve_(eg_D);     
259      } else {
260        add_(eg_C,y);  halve_(eg_C);
261        sub_(eg_D,x);  halve_(eg_D);
262      }
263    }
264
265    if (!greater(v,eg_u)) { //v<=u
266      sub_(eg_u,v);
267      sub_(eg_A,eg_C);
268      sub_(eg_B,eg_D);
269    } else {                //v>u
270      sub_(v,eg_u);
271      sub_(eg_C,eg_A);
272      sub_(eg_D,eg_B);
273    }
274    if (equalsInt(eg_u,0)) {
275      if (negative(eg_C)) {   //make sure a (C)is nonnegative
276        add_(eg_C,y);
277        sub_(eg_D,x);
278      }
279      multInt_(eg_D,-1);  ///make sure b (D) is nonnegative
280      copy_(a,eg_C);
281      copy_(b,eg_D);
282      leftShift_(v,g);
283      return;
284    }
285  }
286}
287
288
289//is bigInt x negative?
290function negative(x) {
291  return ((x[x.length-1]>>(bpe-1))&1);
292}
293
294
295//is (x << (shift*bpe)) > y?
296//x and y are nonnegative bigInts
297//shift is a nonnegative integer
298function greaterShift(x,y,shift) {
299  var i, kx=x.length, ky=y.length;
300  k=((kx+shift)<ky) ? (kx+shift) : ky;
301  for (i=ky-1-shift; i<kx && i>=0; i++)
302    if (x[i]>0)
303      return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger
304  for (i=kx-1+shift; i<ky; i++)
305    if (y[i]>0)
306      return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger
307  for (i=k-1; i>=shift; i--)
308    if      (x[i-shift]>y[i]) return 1;
309    else if (x[i-shift]<y[i]) return 0;
310  return 0;
311}
312
313//is x > y? (x and y both nonnegative)
314function greater(x,y) {
315  var i;
316  var k=(x.length<y.length) ? x.length : y.length;
317
318  for (i=x.length;i<y.length;i++)
319    if (y[i])
320      return 0;  //y has more digits
321
322  for (i=y.length;i<x.length;i++)
323    if (x[i])
324      return 1;  //x has more digits
325
326  for (i=k-1;i>=0;i--)
327    if (x[i]>y[i])
328      return 1;
329    else if (x[i]<y[i])
330      return 0;
331  return 0;
332}
333
334//divide x by y giving quotient q and remainder r.  (q=floor(x/y),  r=x mod y).  All 4 are bigints.
335//x must have at least one leading zero element.
336//y must be nonzero.
337//q and r must be arrays that are exactly the same length as x. (Or q can have more).
338//Must have x.length >= y.length >= 2.
339function divide_(x,y,q,r) {
340  var kx, ky;
341  var i,j,y1,y2,c,a,b;
342  copy_(r,x);
343  for (ky=y.length;y[ky-1]==0;ky--); //ky is number of elements in y, not including leading zeros
344
345  //normalize: ensure the most significant element of y has its highest bit set 
346  b=y[ky-1];
347  for (a=0; b; a++)
348    b>>=1; 
349  a=bpe-a;  //a is how many bits to shift so that the high order bit of y is leftmost in its array element
350  leftShift_(y,a);  //multiply both by 1<<a now, then divide both by that at the end
351  leftShift_(r,a);
352
353  //Rob Visser discovered a bug: the following line was originally just before the normalization.
354  for (kx=r.length;r[kx-1]==0 && kx>ky;kx--); //kx is number of elements in normalized x, not including leading zeros
355
356  copyInt_(q,0);                      // q=0
357  while (!greaterShift(y,r,kx-ky)) {  // while (leftShift_(y,kx-ky) <= r) {
358    subShift_(r,y,kx-ky);             //   r=r-leftShift_(y,kx-ky)
359    q[kx-ky]++;                       //   q[kx-ky]++;
360  }                                   // }
361
362  for (i=kx-1; i>=ky; i--) {
363    if (r[i]==y[ky-1])
364      q[i-ky]=mask;
365    else
366      q[i-ky]=Math.floor((r[i]*radix+r[i-1])/y[ky-1]); 
367
368    //The following for(;;) loop is equivalent to the commented while loop,
369    //except that the uncommented version avoids overflow.
370    //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0
371    //  while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2])
372    //    q[i-ky]--;   
373    for (;;) {
374      y2=(ky>1 ? y[ky-2] : 0)*q[i-ky];
375      c=y2>>bpe;
376      y2=y2 & mask;
377      y1=c+q[i-ky]*y[ky-1];
378      c=y1>>bpe;
379      y1=y1 & mask;
380
381      if (c==r[i] ? y1==r[i-1] ? y2>(i>1 ? r[i-2] : 0) : y1>r[i-1] : c>r[i])
382        q[i-ky]--;
383      else
384        break;
385    }
386
387    linCombShift_(r,y,-q[i-ky],i-ky);    //r=r-q[i-ky]*leftShift_(y,i-ky)
388    if (negative(r)) {
389      addShift_(r,y,i-ky);         //r=r+leftShift_(y,i-ky)
390      q[i-ky]--;
391    }
392  }
393
394  rightShift_(y,a);  //undo the normalization step
395  rightShift_(r,a);  //undo the normalization step
396}
397
398//do carries and borrows so each element of the bigInt x fits in bpe bits.
399function carry_(x) {
400  var i,k,c,b;
401  k=x.length;
402  c=0;
403  for (i=0;i<k;i++) {
404    c+=x[i];
405    b=0;
406    if (c<0) {
407      b=-(c>>bpe);
408      c+=b*radix;
409    }
410    x[i]=c & mask;
411    c=(c>>bpe)-b;
412  }
413}
414
415//return x mod n for bigInt x and integer n.
416function modInt(x,n) {
417  var i,c=0;
418  for (i=x.length-1; i>=0; i--)
419    c=(c*radix+x[i])%n;
420  return c;
421}
422
423//convert the integer t into a bigInt with at least the given number of bits.
424//the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word)
425//Pad the array with leading zeros so that it has at least minSize elements.
426//There will always be at least one leading 0 element.
427function int2bigInt(t,bits,minSize) {   
428  var i,k;
429  k=Math.ceil(bits/bpe)+1;
430  k=minSize>k ? minSize : k;
431  buff=new Array(k);
432  copyInt_(buff,t);
433  return buff;
434}
435
436//return the bigInt given a string representation in a given base. 
437//Pad the array with leading zeros so that it has at least minSize elements.
438//If base=-1, then it reads in a space-separated list of array elements in decimal.
439//The array will always have at least one leading zero, unless base=-1.
440function str2bigInt(s,base,minSize) {
441  var d, i, j, x, y, kk;
442  var k=s.length;
443  if (base==-1) { //comma-separated list of array elements in decimal
444    x=new Array(0);
445    for (;;) {
446      y=new Array(x.length+1);
447      for (i=0;i<x.length;i++)
448        y[i+1]=x[i];
449      y[0]=parseInt(s,10);
450      x=y;
451      d=s.indexOf(',',0);
452      if (d<1)
453        break;
454      s=s.substring(d+1);
455      if (s.length==0)
456        break;
457    }
458    if (x.length<minSize) {
459      y=new Array(minSize);
460      copy_(y,x);
461      return y;
462    }
463    return x;
464  }
465
466  x=int2bigInt(0,base*k,0);
467  for (i=0;i<k;i++) {
468    d=digitsStr.indexOf(s.substring(i,i+1),0);
469    if (base<=36 && d>=36)  //convert lowercase to uppercase if base<=36
470      d-=26;
471    if (d>=base || d<0) {   //stop at first illegal character
472      break;
473    }
474    multInt_(x,base);
475    addInt_(x,d);
476  }
477
478  for (k=x.length;k>0 && !x[k-1];k--); //strip off leading zeros
479  k=minSize>k+1 ? minSize : k+1;
480  y=new Array(k);
481  kk=k<x.length ? k : x.length;
482  for (i=0;i<kk;i++)
483    y[i]=x[i];
484  for (;i<k;i++)
485    y[i]=0;
486  return y;
487}
488
489//is bigint x equal to integer y?
490//y must have less than bpe bits
491function equalsInt(x,y) {
492  var i;
493  if (x[0]!=y)
494    return 0;
495  for (i=1;i<x.length;i++)
496    if (x[i])
497      return 0;
498  return 1;
499}
500
501//are bigints x and y equal?
502//this works even if x and y are different lengths and have arbitrarily many leading zeros
503function equals(x,y) {
504  var i;
505  var k=x.length<y.length ? x.length : y.length;
506  for (i=0;i<k;i++)
507    if (x[i]!=y[i])
508      return 0;
509  if (x.length>y.length) {
510    for (;i<x.length;i++)
511      if (x[i])
512        return 0;
513  } else {
514    for (;i<y.length;i++)
515      if (y[i])
516        return 0;
517  }
518  return 1;
519}
520
521//is the bigInt x equal to zero?
522function isZero(x) {
523  var i;
524  for (i=0;i<x.length;i++)
525    if (x[i])
526      return 0;
527  return 1;
528}
529
530//convert a bigInt into a string in a given base, from base 2 up to base 95.
531//Base -1 prints the contents of the array representing the number.
532function bigInt2str(x,base) {
533  var i,t,s="";
534
535  if (s6.length!=x.length)
536    s6=dup(x);
537  else
538    copy_(s6,x);
539
540  if (base==-1) { //return the list of array contents
541    for (i=x.length-1;i>0;i--)
542      s+=x[i]+',';
543    s+=x[0];
544  }
545  else { //return it in the given base
546    while (!isZero(s6)) {
547      t=divInt_(s6,base);  //t=s6 % base; s6=floor(s6/base);
548      s=digitsStr.substring(t,t+1)+s;
549    }
550  }
551  if (s.length==0)
552    s="0";
553  return s;
554}
555
556//returns a duplicate of bigInt x
557function dup(x) {
558  var i;
559  buff=new Array(x.length);
560  copy_(buff,x);
561  return buff;
562}
563
564//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).
565function copy_(x,y) {
566  var i;
567  var k=x.length<y.length ? x.length : y.length;
568  for (i=0;i<k;i++)
569    x[i]=y[i];
570  for (i=k;i<x.length;i++)
571    x[i]=0;
572}
573
574//do x=y on bigInt x and integer y. 
575function copyInt_(x,n) {
576  var i,c;
577  for (c=n,i=0;i<x.length;i++) {
578    x[i]=c & mask;
579    c>>=bpe;
580  }
581}
582
583//do x=x+n where x is a bigInt and n is an integer.
584//x must be large enough to hold the result.
585function addInt_(x,n) {
586  var i,k,c,b;
587  x[0]+=n;
588  k=x.length;
589  c=0;
590  for (i=0;i<k;i++) {
591    c+=x[i];
592    b=0;
593    if (c<0) {
594      b=-(c>>bpe);
595      c+=b*radix;
596    }
597    x[i]=c & mask;
598    c=(c>>bpe)-b;
599    if (!c) return; //stop carrying as soon as the carry is zero
600  }
601}
602
603//right shift bigInt x by n bits.  0 <= n < bpe.
604function rightShift_(x,n) {
605  var i;
606  var k=Math.floor(n/bpe);
607  if (k) {
608    for (i=0;i<x.length-k;i++) //right shift x by k elements
609      x[i]=x[i+k];
610    for (;i<x.length;i++)
611      x[i]=0;
612    n%=bpe;
613  }
614  for (i=0;i<x.length-1;i++) {
615    x[i]=mask & ((x[i+1]<<(bpe-n)) | (x[i]>>n));
616  }
617  x[i]>>=n;
618}
619
620//do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
621function halve_(x) {
622  var i;
623  for (i=0;i<x.length-1;i++) {
624    x[i]=mask & ((x[i+1]<<(bpe-1)) | (x[i]>>1));
625  }
626  x[i]=(x[i]>>1) | (x[i] & (radix>>1));  //most significant bit stays the same
627}
628
629//left shift bigInt x by n bits.
630function leftShift_(x,n) {
631  var i;
632  var k=Math.floor(n/bpe);
633  if (k) {
634    for (i=x.length; i>=k; i--) //left shift x by k elements
635      x[i]=x[i-k];
636    for (;i>=0;i--)
637      x[i]=0; 
638    n%=bpe;
639  }
640  if (!n)
641    return;
642  for (i=x.length-1;i>0;i--) {
643    x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n)));
644  }
645  x[i]=mask & (x[i]<<n);
646}
647
648//do x=x*n where x is a bigInt and n is an integer.
649//x must be large enough to hold the result.
650function multInt_(x,n) {
651  var i,k,c,b;
652  if (!n)
653    return;
654  k=x.length;
655  c=0;
656  for (i=0;i<k;i++) {
657    c+=x[i]*n;
658    b=0;
659    if (c<0) {
660      b=-(c>>bpe);
661      c+=b*radix;
662    }
663    x[i]=c & mask;
664    c=(c>>bpe)-b;
665  }
666}
667
668//do x=floor(x/n) for bigInt x and integer n, and return the remainder
669function divInt_(x,n) {
670  var i,r=0,s;
671  for (i=x.length-1;i>=0;i--) {
672    s=r*radix+x[i];
673    x[i]=Math.floor(s/n);
674    r=s%n;
675  }
676  return r;
677}
678
679//do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b.
680//x must be large enough to hold the answer.
681function linComb_(x,y,a,b) {
682  var i,c,k,kk;
683  k=x.length<y.length ? x.length : y.length;
684  kk=x.length;
685  for (c=0,i=0;i<k;i++) {
686    c+=a*x[i]+b*y[i];
687    x[i]=c & mask;
688    c>>=bpe;
689  }
690  for (i=k;i<kk;i++) {
691    c+=a*x[i];
692    x[i]=c & mask;
693    c>>=bpe;
694  }
695}
696
697//do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys.
698//x must be large enough to hold the answer.
699function linCombShift_(x,y,b,ys) {
700  var i,c,k,kk;
701  k=x.length<ys+y.length ? x.length : ys+y.length;
702  kk=x.length;
703  for (c=0,i=ys;i<k;i++) {
704    c+=x[i]+b*y[i-ys];
705    x[i]=c & mask;
706    c>>=bpe;
707  }
708  for (i=k;c && i<kk;i++) {
709    c+=x[i];
710    x[i]=c & mask;
711    c>>=bpe;
712  }
713}
714
715//do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
716//x must be large enough to hold the answer.
717function addShift_(x,y,ys) {
718  var i,c,k,kk;
719  k=x.length<ys+y.length ? x.length : ys+y.length;
720  kk=x.length;
721  for (c=0,i=ys;i<k;i++) {
722    c+=x[i]+y[i-ys];
723    x[i]=c & mask;
724    c>>=bpe;
725  }
726  for (i=k;c && i<kk;i++) {
727    c+=x[i];
728    x[i]=c & mask;
729    c>>=bpe;
730  }
731}
732
733//do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
734//x must be large enough to hold the answer.
735function subShift_(x,y,ys) {
736  var i,c,k,kk;
737  k=x.length<ys+y.length ? x.length : ys+y.length;
738  kk=x.length;
739  for (c=0,i=ys;i<k;i++) {
740    c+=x[i]-y[i-ys];
741    x[i]=c & mask;
742    c>>=bpe;
743  }
744  for (i=k;c && i<kk;i++) {
745    c+=x[i];
746    x[i]=c & mask;
747    c>>=bpe;
748  }
749}
750
751//do x=x-y for bigInts x and y.
752//x must be large enough to hold the answer.
753//negative answers will be 2s complement
754function sub_(x,y) {
755  var i,c,k,kk;
756  k=x.length<y.length ? x.length : y.length;
757  for (c=0,i=0;i<k;i++) {
758    c+=x[i]-y[i];
759    x[i]=c & mask;
760    c>>=bpe;
761  }
762  for (i=k;c && i<x.length;i++) {
763    c+=x[i];
764    x[i]=c & mask;
765    c>>=bpe;
766  }
767}
768
769//do x=x+y for bigInts x and y.
770//x must be large enough to hold the answer.
771function add_(x,y) {
772  var i,c,k,kk;
773  k=x.length<y.length ? x.length : y.length;
774  for (c=0,i=0;i<k;i++) {
775    c+=x[i]+y[i];
776    x[i]=c & mask;
777    c>>=bpe;
778  }
779  for (i=k;c && i<x.length;i++) {
780    c+=x[i];
781    x[i]=c & mask;
782    c>>=bpe;
783  }
784}
785
786//do x=x*y for bigInts x and y.  This is faster when y<x.
787function mult_(x,y) {
788  var i;
789  if (ss.length!=2*x.length)
790    ss=new Array(2*x.length);
791  copyInt_(ss,0);
792  for (i=0;i<y.length;i++)
793    if (y[i])
794      linCombShift_(ss,x,y[i],i);   //ss=1*ss+y[i]*(x<<(i*bpe))
795  copy_(x,ss);
796}
797
798//do x=x mod n for bigInts x and n.
799function mod_(x,n) {
800  if (s4.length!=x.length)
801    s4=dup(x);
802  else
803    copy_(s4,x);
804  if (s5.length!=x.length)
805    s5=dup(x); 
806  divide_(s4,n,s5,x);  //x = remainder of s4 / n
807}
808
809//do x=x*y mod n for bigInts x,y,n.
810//for greater speed, let y<x.
811function multMod_(x,y,n) {
812  var i;
813  if (s0.length!=2*x.length)
814    s0=new Array(2*x.length);
815  copyInt_(s0,0);
816  for (i=0;i<y.length;i++)
817    if (y[i])
818      linCombShift_(s0,x,y[i],i);   //s0=1*s0+y[i]*(x<<(i*bpe))
819  mod_(s0,n);
820  copy_(x,s0);
821}
822
823//do x=x*x mod n for bigInts x,n.
824function squareMod_(x,n) {
825  var i,j,d,c,kx,kn,k;
826  for (kx=x.length; kx>0 && !x[kx-1]; kx--);  //ignore leading zeros in x
827  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
828  if (s0.length!=k)
829    s0=new Array(k);
830  copyInt_(s0,0);
831  for (i=0;i<kx;i++) {
832    c=s0[2*i]+x[i]*x[i];
833    s0[2*i]=c & mask;
834    c>>=bpe;
835    for (j=i+1;j<kx;j++) {
836      c=s0[i+j]+2*x[i]*x[j]+c;
837      s0[i+j]=(c & mask);
838      c>>=bpe;
839    }
840    s0[i+kx]=c;
841  }
842  mod_(s0,n);
843  copy_(x,s0);
844}
845
846//return x with exactly k leading zero elements
847function bigintTrim(x,k) {
848  var i,y;
849  for (i=x.length; i>0 && !x[i-1]; i--);
850  y=new Array(i+k);
851  copy_(y,x);
852  return y;
853}
854
855//do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation.  0**0=1.
856//this is faster when n is odd.  x usually needs to have as many elements as n.
857function powMod_(x,y,n) {
858  var k1,k2,kn,np;
859  if(s7.length!=n.length)
860    s7=dup(n);
861
862  //for even modulus, use a simple square-and-multiply algorithm,
863  //rather than using the more complex Montgomery algorithm.
864  if ((n[0]&1)==0) {
865    copy_(s7,x);
866    copyInt_(x,1);
867    while(!equalsInt(y,0)) {
868      if (y[0]&1)
869        multMod_(x,s7,n);
870      divInt_(y,2);
871      squareMod_(s7,n);
872    }
873    return;
874  }
875
876  //calculate np from n for the Montgomery multiplications
877  copyInt_(s7,0);
878  for (kn=n.length;kn>0 && !n[kn-1];kn--);
879  np=radix-inverseModInt(modInt(n,radix),radix);
880  s7[kn]=1;
881  multMod_(x ,s7,n);   // x = x * 2**(kn*bp) mod n
882
883  if (s3.length!=x.length)
884    s3=dup(x);
885  else
886    copy_(s3,x);
887
888  for (k1=y.length-1;k1>0 & !y[k1]; k1--);  //k1=first nonzero element of y
889  if (y[k1]==0) {  //anything to the 0th power is 1
890    copyInt_(x,1);
891    return;
892  }
893  for (k2=1<<(bpe-1);k2 && !(y[k1] & k2); k2>>=1);  //k2=position of first 1 bit in y[k1]
894  for (;;) {
895    if (!(k2>>=1)) {  //look at next bit of y
896      k1--;
897      if (k1<0) {
898        mont_(x,one,n,np);
899        return;
900      }
901      k2=1<<(bpe-1);
902    }   
903    mont_(x,x,n,np);
904
905    if (k2 & y[k1]) //if next bit is a 1
906      mont_(x,s3,n,np);
907  }
908}
909
910
911//do x=x*y*Ri mod n for bigInts x,y,n,
912//  where Ri = 2**(-kn*bpe) mod n, and kn is the
913//  number of elements in the n array, not
914//  counting leading zeros. 
915//x array must have at least as many elemnts as the n array
916//It's OK if x and y are the same variable.
917//must have:
918//  x,y < n
919//  n is odd
920//  np = -(n^(-1)) mod radix
921function mont_(x,y,n,np) {
922  var i,j,c,ui,t,ks;
923  var kn=n.length;
924  var ky=y.length;
925
926  if (sa.length!=kn)
927    sa=new Array(kn);
928   
929  copyInt_(sa,0);
930
931  for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n
932  for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y
933  ks=sa.length-1; //sa will never have more than this many nonzero elements. 
934
935  //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers
936  for (i=0; i<kn; i++) {
937    t=sa[0]+x[i]*y[0];
938    ui=((t & mask) * np) & mask;  //the inner "& mask" was needed on Safari (but not MSIE) at one time
939    c=(t+ui*n[0]) >> bpe;
940    t=x[i];
941   
942    //do sa=(sa+x[i]*y+ui*n)/b   where b=2**bpe.  Loop is unrolled 5-fold for speed
943    j=1;
944    for (;j<ky-4;) { c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
945                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
946                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
947                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
948                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++; }   
949    for (;j<ky;)   { c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++; }
950    for (;j<kn-4;) { c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
951                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
952                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
953                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
954                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++; } 
955    for (;j<kn;)   { c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++; }   
956    for (;j<ks;)   { c+=sa[j];                  sa[j-1]=c & mask;   c>>=bpe;   j++; } 
957    sa[j-1]=c & mask;
958  }
959
960  if (!greater(n,sa))
961    sub_(sa,n);
962  copy_(x,sa);
963}
964
965
Note: See TracBrowser for help on using the repository browser.