OSDN Git Service

libgo: Update to weekly.2011-11-18.
[pf3gnuchains/gcc-fork.git] / libgo / go / math / big / int.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // This file implements signed multi-precision integers.
6
7 package big
8
9 import (
10         "errors"
11         "fmt"
12         "io"
13         "math/rand"
14         "strings"
15 )
16
17 // An Int represents a signed multi-precision integer.
18 // The zero value for an Int represents the value 0.
19 type Int struct {
20         neg bool // sign
21         abs nat  // absolute value of the integer
22 }
23
24 var intOne = &Int{false, natOne}
25
26 // Sign returns:
27 //
28 //      -1 if x <  0
29 //       0 if x == 0
30 //      +1 if x >  0
31 //
32 func (x *Int) Sign() int {
33         if len(x.abs) == 0 {
34                 return 0
35         }
36         if x.neg {
37                 return -1
38         }
39         return 1
40 }
41
42 // SetInt64 sets z to x and returns z.
43 func (z *Int) SetInt64(x int64) *Int {
44         neg := false
45         if x < 0 {
46                 neg = true
47                 x = -x
48         }
49         z.abs = z.abs.setUint64(uint64(x))
50         z.neg = neg
51         return z
52 }
53
54 // NewInt allocates and returns a new Int set to x.
55 func NewInt(x int64) *Int {
56         return new(Int).SetInt64(x)
57 }
58
59 // Set sets z to x and returns z.
60 func (z *Int) Set(x *Int) *Int {
61         if z != x {
62                 z.abs = z.abs.set(x.abs)
63                 z.neg = x.neg
64         }
65         return z
66 }
67
68 // Abs sets z to |x| (the absolute value of x) and returns z.
69 func (z *Int) Abs(x *Int) *Int {
70         z.Set(x)
71         z.neg = false
72         return z
73 }
74
75 // Neg sets z to -x and returns z.
76 func (z *Int) Neg(x *Int) *Int {
77         z.Set(x)
78         z.neg = len(z.abs) > 0 && !z.neg // 0 has no sign
79         return z
80 }
81
82 // Add sets z to the sum x+y and returns z.
83 func (z *Int) Add(x, y *Int) *Int {
84         neg := x.neg
85         if x.neg == y.neg {
86                 // x + y == x + y
87                 // (-x) + (-y) == -(x + y)
88                 z.abs = z.abs.add(x.abs, y.abs)
89         } else {
90                 // x + (-y) == x - y == -(y - x)
91                 // (-x) + y == y - x == -(x - y)
92                 if x.abs.cmp(y.abs) >= 0 {
93                         z.abs = z.abs.sub(x.abs, y.abs)
94                 } else {
95                         neg = !neg
96                         z.abs = z.abs.sub(y.abs, x.abs)
97                 }
98         }
99         z.neg = len(z.abs) > 0 && neg // 0 has no sign
100         return z
101 }
102
103 // Sub sets z to the difference x-y and returns z.
104 func (z *Int) Sub(x, y *Int) *Int {
105         neg := x.neg
106         if x.neg != y.neg {
107                 // x - (-y) == x + y
108                 // (-x) - y == -(x + y)
109                 z.abs = z.abs.add(x.abs, y.abs)
110         } else {
111                 // x - y == x - y == -(y - x)
112                 // (-x) - (-y) == y - x == -(x - y)
113                 if x.abs.cmp(y.abs) >= 0 {
114                         z.abs = z.abs.sub(x.abs, y.abs)
115                 } else {
116                         neg = !neg
117                         z.abs = z.abs.sub(y.abs, x.abs)
118                 }
119         }
120         z.neg = len(z.abs) > 0 && neg // 0 has no sign
121         return z
122 }
123
124 // Mul sets z to the product x*y and returns z.
125 func (z *Int) Mul(x, y *Int) *Int {
126         // x * y == x * y
127         // x * (-y) == -(x * y)
128         // (-x) * y == -(x * y)
129         // (-x) * (-y) == x * y
130         z.abs = z.abs.mul(x.abs, y.abs)
131         z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
132         return z
133 }
134
135 // MulRange sets z to the product of all integers
136 // in the range [a, b] inclusively and returns z.
137 // If a > b (empty range), the result is 1.
138 func (z *Int) MulRange(a, b int64) *Int {
139         switch {
140         case a > b:
141                 return z.SetInt64(1) // empty range
142         case a <= 0 && b >= 0:
143                 return z.SetInt64(0) // range includes 0
144         }
145         // a <= b && (b < 0 || a > 0)
146
147         neg := false
148         if a < 0 {
149                 neg = (b-a)&1 == 0
150                 a, b = -b, -a
151         }
152
153         z.abs = z.abs.mulRange(uint64(a), uint64(b))
154         z.neg = neg
155         return z
156 }
157
158 // Binomial sets z to the binomial coefficient of (n, k) and returns z.
159 func (z *Int) Binomial(n, k int64) *Int {
160         var a, b Int
161         a.MulRange(n-k+1, n)
162         b.MulRange(1, k)
163         return z.Quo(&a, &b)
164 }
165
166 // Quo sets z to the quotient x/y for y != 0 and returns z.
167 // If y == 0, a division-by-zero run-time panic occurs.
168 // Quo implements truncated division (like Go); see QuoRem for more details.
169 func (z *Int) Quo(x, y *Int) *Int {
170         z.abs, _ = z.abs.div(nil, x.abs, y.abs)
171         z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
172         return z
173 }
174
175 // Rem sets z to the remainder x%y for y != 0 and returns z.
176 // If y == 0, a division-by-zero run-time panic occurs.
177 // Rem implements truncated modulus (like Go); see QuoRem for more details.
178 func (z *Int) Rem(x, y *Int) *Int {
179         _, z.abs = nat(nil).div(z.abs, x.abs, y.abs)
180         z.neg = len(z.abs) > 0 && x.neg // 0 has no sign
181         return z
182 }
183
184 // QuoRem sets z to the quotient x/y and r to the remainder x%y
185 // and returns the pair (z, r) for y != 0.
186 // If y == 0, a division-by-zero run-time panic occurs.
187 //
188 // QuoRem implements T-division and modulus (like Go):
189 //
190 //      q = x/y      with the result truncated to zero
191 //      r = x - y*q
192 //
193 // (See Daan Leijen, ``Division and Modulus for Computer Scientists''.)
194 //
195 func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
196         z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs)
197         z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign
198         return z, r
199 }
200
201 // Div sets z to the quotient x/y for y != 0 and returns z.
202 // If y == 0, a division-by-zero run-time panic occurs.
203 // Div implements Euclidean division (unlike Go); see DivMod for more details.
204 func (z *Int) Div(x, y *Int) *Int {
205         y_neg := y.neg // z may be an alias for y
206         var r Int
207         z.QuoRem(x, y, &r)
208         if r.neg {
209                 if y_neg {
210                         z.Add(z, intOne)
211                 } else {
212                         z.Sub(z, intOne)
213                 }
214         }
215         return z
216 }
217
218 // Mod sets z to the modulus x%y for y != 0 and returns z.
219 // If y == 0, a division-by-zero run-time panic occurs.
220 // Mod implements Euclidean modulus (unlike Go); see DivMod for more details.
221 func (z *Int) Mod(x, y *Int) *Int {
222         y0 := y // save y
223         if z == y || alias(z.abs, y.abs) {
224                 y0 = new(Int).Set(y)
225         }
226         var q Int
227         q.QuoRem(x, y, z)
228         if z.neg {
229                 if y0.neg {
230                         z.Sub(z, y0)
231                 } else {
232                         z.Add(z, y0)
233                 }
234         }
235         return z
236 }
237
238 // DivMod sets z to the quotient x div y and m to the modulus x mod y
239 // and returns the pair (z, m) for y != 0.
240 // If y == 0, a division-by-zero run-time panic occurs.
241 //
242 // DivMod implements Euclidean division and modulus (unlike Go):
243 //
244 //      q = x div y  such that
245 //      m = x - y*q  with 0 <= m < |q|
246 //
247 // (See Raymond T. Boute, ``The Euclidean definition of the functions
248 // div and mod''. ACM Transactions on Programming Languages and
249 // Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.
250 // ACM press.)
251 //
252 func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
253         y0 := y // save y
254         if z == y || alias(z.abs, y.abs) {
255                 y0 = new(Int).Set(y)
256         }
257         z.QuoRem(x, y, m)
258         if m.neg {
259                 if y0.neg {
260                         z.Add(z, intOne)
261                         m.Sub(m, y0)
262                 } else {
263                         z.Sub(z, intOne)
264                         m.Add(m, y0)
265                 }
266         }
267         return z, m
268 }
269
270 // Cmp compares x and y and returns:
271 //
272 //   -1 if x <  y
273 //    0 if x == y
274 //   +1 if x >  y
275 //
276 func (x *Int) Cmp(y *Int) (r int) {
277         // x cmp y == x cmp y
278         // x cmp (-y) == x
279         // (-x) cmp y == y
280         // (-x) cmp (-y) == -(x cmp y)
281         switch {
282         case x.neg == y.neg:
283                 r = x.abs.cmp(y.abs)
284                 if x.neg {
285                         r = -r
286                 }
287         case x.neg:
288                 r = -1
289         default:
290                 r = 1
291         }
292         return
293 }
294
295 func (x *Int) String() string {
296         switch {
297         case x == nil:
298                 return "<nil>"
299         case x.neg:
300                 return "-" + x.abs.decimalString()
301         }
302         return x.abs.decimalString()
303 }
304
305 func charset(ch rune) string {
306         switch ch {
307         case 'b':
308                 return lowercaseDigits[0:2]
309         case 'o':
310                 return lowercaseDigits[0:8]
311         case 'd', 's', 'v':
312                 return lowercaseDigits[0:10]
313         case 'x':
314                 return lowercaseDigits[0:16]
315         case 'X':
316                 return uppercaseDigits[0:16]
317         }
318         return "" // unknown format
319 }
320
321 // write count copies of text to s
322 func writeMultiple(s fmt.State, text string, count int) {
323         if len(text) > 0 {
324                 b := []byte(text)
325                 for ; count > 0; count-- {
326                         s.Write(b)
327                 }
328         }
329 }
330
331 // Format is a support routine for fmt.Formatter. It accepts
332 // the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x'
333 // (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
334 // Also supported are the full suite of package fmt's format
335 // verbs for integral types, including '+', '-', and ' '
336 // for sign control, '#' for leading zero in octal and for
337 // hexadecimal, a leading "0x" or "0X" for "%#x" and "%#X"
338 // respectively, specification of minimum digits precision,
339 // output field width, space or zero padding, and left or
340 // right justification.
341 //
342 func (x *Int) Format(s fmt.State, ch rune) {
343         cs := charset(ch)
344
345         // special cases
346         switch {
347         case cs == "":
348                 // unknown format
349                 fmt.Fprintf(s, "%%!%c(big.Int=%s)", ch, x.String())
350                 return
351         case x == nil:
352                 fmt.Fprint(s, "<nil>")
353                 return
354         }
355
356         // determine sign character
357         sign := ""
358         switch {
359         case x.neg:
360                 sign = "-"
361         case s.Flag('+'): // supersedes ' ' when both specified
362                 sign = "+"
363         case s.Flag(' '):
364                 sign = " "
365         }
366
367         // determine prefix characters for indicating output base
368         prefix := ""
369         if s.Flag('#') {
370                 switch ch {
371                 case 'o': // octal
372                         prefix = "0"
373                 case 'x': // hexadecimal
374                         prefix = "0x"
375                 case 'X':
376                         prefix = "0X"
377                 }
378         }
379
380         // determine digits with base set by len(cs) and digit characters from cs
381         digits := x.abs.string(cs)
382
383         // number of characters for the three classes of number padding
384         var left int   // space characters to left of digits for right justification ("%8d")
385         var zeroes int // zero characters (actually cs[0]) as left-most digits ("%.8d")
386         var right int  // space characters to right of digits for left justification ("%-8d")
387
388         // determine number padding from precision: the least number of digits to output
389         precision, precisionSet := s.Precision()
390         if precisionSet {
391                 switch {
392                 case len(digits) < precision:
393                         zeroes = precision - len(digits) // count of zero padding 
394                 case digits == "0" && precision == 0:
395                         return // print nothing if zero value (x == 0) and zero precision ("." or ".0")
396                 }
397         }
398
399         // determine field pad from width: the least number of characters to output
400         length := len(sign) + len(prefix) + zeroes + len(digits)
401         if width, widthSet := s.Width(); widthSet && length < width { // pad as specified
402                 switch d := width - length; {
403                 case s.Flag('-'):
404                         // pad on the right with spaces; supersedes '0' when both specified
405                         right = d
406                 case s.Flag('0') && !precisionSet:
407                         // pad with zeroes unless precision also specified
408                         zeroes = d
409                 default:
410                         // pad on the left with spaces
411                         left = d
412                 }
413         }
414
415         // print number as [left pad][sign][prefix][zero pad][digits][right pad]
416         writeMultiple(s, " ", left)
417         writeMultiple(s, sign, 1)
418         writeMultiple(s, prefix, 1)
419         writeMultiple(s, "0", zeroes)
420         writeMultiple(s, digits, 1)
421         writeMultiple(s, " ", right)
422 }
423
424 // scan sets z to the integer value corresponding to the longest possible prefix
425 // read from r representing a signed integer number in a given conversion base.
426 // It returns z, the actual conversion base used, and an error, if any. In the
427 // error case, the value of z is undefined but the returned value is nil. The
428 // syntax follows the syntax of integer literals in Go.
429 //
430 // The base argument must be 0 or a value from 2 through MaxBase. If the base
431 // is 0, the string prefix determines the actual conversion base. A prefix of
432 // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
433 // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
434 //
435 func (z *Int) scan(r io.RuneScanner, base int) (*Int, int, error) {
436         // determine sign
437         ch, _, err := r.ReadRune()
438         if err != nil {
439                 return nil, 0, err
440         }
441         neg := false
442         switch ch {
443         case '-':
444                 neg = true
445         case '+': // nothing to do
446         default:
447                 r.UnreadRune()
448         }
449
450         // determine mantissa
451         z.abs, base, err = z.abs.scan(r, base)
452         if err != nil {
453                 return nil, base, err
454         }
455         z.neg = len(z.abs) > 0 && neg // 0 has no sign
456
457         return z, base, nil
458 }
459
460 // Scan is a support routine for fmt.Scanner; it sets z to the value of
461 // the scanned number. It accepts the formats 'b' (binary), 'o' (octal),
462 // 'd' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal).
463 func (z *Int) Scan(s fmt.ScanState, ch rune) error {
464         s.SkipSpace() // skip leading space characters
465         base := 0
466         switch ch {
467         case 'b':
468                 base = 2
469         case 'o':
470                 base = 8
471         case 'd':
472                 base = 10
473         case 'x', 'X':
474                 base = 16
475         case 's', 'v':
476                 // let scan determine the base
477         default:
478                 return errors.New("Int.Scan: invalid verb")
479         }
480         _, _, err := z.scan(s, base)
481         return err
482 }
483
484 // Int64 returns the int64 representation of x.
485 // If x cannot be represented in an int64, the result is undefined.
486 func (x *Int) Int64() int64 {
487         if len(x.abs) == 0 {
488                 return 0
489         }
490         v := int64(x.abs[0])
491         if _W == 32 && len(x.abs) > 1 {
492                 v |= int64(x.abs[1]) << 32
493         }
494         if x.neg {
495                 v = -v
496         }
497         return v
498 }
499
500 // SetString sets z to the value of s, interpreted in the given base,
501 // and returns z and a boolean indicating success. If SetString fails,
502 // the value of z is undefined but the returned value is nil.
503 //
504 // The base argument must be 0 or a value from 2 through MaxBase. If the base
505 // is 0, the string prefix determines the actual conversion base. A prefix of
506 // ``0x'' or ``0X'' selects base 16; the ``0'' prefix selects base 8, and a
507 // ``0b'' or ``0B'' prefix selects base 2. Otherwise the selected base is 10.
508 //
509 func (z *Int) SetString(s string, base int) (*Int, bool) {
510         r := strings.NewReader(s)
511         _, _, err := z.scan(r, base)
512         if err != nil {
513                 return nil, false
514         }
515         _, _, err = r.ReadRune()
516         if err != io.EOF {
517                 return nil, false
518         }
519         return z, true // err == io.EOF => scan consumed all of s
520 }
521
522 // SetBytes interprets buf as the bytes of a big-endian unsigned
523 // integer, sets z to that value, and returns z.
524 func (z *Int) SetBytes(buf []byte) *Int {
525         z.abs = z.abs.setBytes(buf)
526         z.neg = false
527         return z
528 }
529
530 // Bytes returns the absolute value of z as a big-endian byte slice.
531 func (z *Int) Bytes() []byte {
532         buf := make([]byte, len(z.abs)*_S)
533         return buf[z.abs.bytes(buf):]
534 }
535
536 // BitLen returns the length of the absolute value of z in bits.
537 // The bit length of 0 is 0.
538 func (z *Int) BitLen() int {
539         return z.abs.bitLen()
540 }
541
542 // Exp sets z = x**y mod m. If m is nil, z = x**y.
543 // See Knuth, volume 2, section 4.6.3.
544 func (z *Int) Exp(x, y, m *Int) *Int {
545         if y.neg || len(y.abs) == 0 {
546                 neg := x.neg
547                 z.SetInt64(1)
548                 z.neg = neg
549                 return z
550         }
551
552         var mWords nat
553         if m != nil {
554                 mWords = m.abs
555         }
556
557         z.abs = z.abs.expNN(x.abs, y.abs, mWords)
558         z.neg = len(z.abs) > 0 && x.neg && y.abs[0]&1 == 1 // 0 has no sign
559         return z
560 }
561
562 // GcdInt sets d to the greatest common divisor of a and b, which must be
563 // positive numbers.
564 // If x and y are not nil, GcdInt sets x and y such that d = a*x + b*y.
565 // If either a or b is not positive, GcdInt sets d = x = y = 0.
566 func GcdInt(d, x, y, a, b *Int) {
567         if a.neg || b.neg {
568                 d.SetInt64(0)
569                 if x != nil {
570                         x.SetInt64(0)
571                 }
572                 if y != nil {
573                         y.SetInt64(0)
574                 }
575                 return
576         }
577
578         A := new(Int).Set(a)
579         B := new(Int).Set(b)
580
581         X := new(Int)
582         Y := new(Int).SetInt64(1)
583
584         lastX := new(Int).SetInt64(1)
585         lastY := new(Int)
586
587         q := new(Int)
588         temp := new(Int)
589
590         for len(B.abs) > 0 {
591                 r := new(Int)
592                 q, r = q.QuoRem(A, B, r)
593
594                 A, B = B, r
595
596                 temp.Set(X)
597                 X.Mul(X, q)
598                 X.neg = !X.neg
599                 X.Add(X, lastX)
600                 lastX.Set(temp)
601
602                 temp.Set(Y)
603                 Y.Mul(Y, q)
604                 Y.neg = !Y.neg
605                 Y.Add(Y, lastY)
606                 lastY.Set(temp)
607         }
608
609         if x != nil {
610                 *x = *lastX
611         }
612
613         if y != nil {
614                 *y = *lastY
615         }
616
617         *d = *A
618 }
619
620 // ProbablyPrime performs n Miller-Rabin tests to check whether z is prime.
621 // If it returns true, z is prime with probability 1 - 1/4^n.
622 // If it returns false, z is not prime.
623 func ProbablyPrime(z *Int, n int) bool {
624         return !z.neg && z.abs.probablyPrime(n)
625 }
626
627 // Rand sets z to a pseudo-random number in [0, n) and returns z.
628 func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int {
629         z.neg = false
630         if n.neg == true || len(n.abs) == 0 {
631                 z.abs = nil
632                 return z
633         }
634         z.abs = z.abs.random(rnd, n.abs, n.abs.bitLen())
635         return z
636 }
637
638 // ModInverse sets z to the multiplicative inverse of g in the group â„¤/pℤ (where
639 // p is a prime) and returns z.
640 func (z *Int) ModInverse(g, p *Int) *Int {
641         var d Int
642         GcdInt(&d, z, nil, g, p)
643         // x and y are such that g*x + p*y = d. Since p is prime, d = 1. Taking
644         // that modulo p results in g*x = 1, therefore x is the inverse element.
645         if z.neg {
646                 z.Add(z, p)
647         }
648         return z
649 }
650
651 // Lsh sets z = x << n and returns z.
652 func (z *Int) Lsh(x *Int, n uint) *Int {
653         z.abs = z.abs.shl(x.abs, n)
654         z.neg = x.neg
655         return z
656 }
657
658 // Rsh sets z = x >> n and returns z.
659 func (z *Int) Rsh(x *Int, n uint) *Int {
660         if x.neg {
661                 // (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
662                 t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
663                 t = t.shr(t, n)
664                 z.abs = t.add(t, natOne)
665                 z.neg = true // z cannot be zero if x is negative
666                 return z
667         }
668
669         z.abs = z.abs.shr(x.abs, n)
670         z.neg = false
671         return z
672 }
673
674 // Bit returns the value of the i'th bit of z. That is, it
675 // returns (z>>i)&1. The bit index i must be >= 0.
676 func (z *Int) Bit(i int) uint {
677         if i < 0 {
678                 panic("negative bit index")
679         }
680         if z.neg {
681                 t := nat(nil).sub(z.abs, natOne)
682                 return t.bit(uint(i)) ^ 1
683         }
684
685         return z.abs.bit(uint(i))
686 }
687
688 // SetBit sets z to x, with x's i'th bit set to b (0 or 1).
689 // That is, if bit is 1 SetBit sets z = x | (1 << i);
690 // if bit is 0 it sets z = x &^ (1 << i). If bit is not 0 or 1,
691 // SetBit will panic.
692 func (z *Int) SetBit(x *Int, i int, b uint) *Int {
693         if i < 0 {
694                 panic("negative bit index")
695         }
696         if x.neg {
697                 t := z.abs.sub(x.abs, natOne)
698                 t = t.setBit(t, uint(i), b^1)
699                 z.abs = t.add(t, natOne)
700                 z.neg = len(z.abs) > 0
701                 return z
702         }
703         z.abs = z.abs.setBit(x.abs, uint(i), b)
704         z.neg = false
705         return z
706 }
707
708 // And sets z = x & y and returns z.
709 func (z *Int) And(x, y *Int) *Int {
710         if x.neg == y.neg {
711                 if x.neg {
712                         // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
713                         x1 := nat(nil).sub(x.abs, natOne)
714                         y1 := nat(nil).sub(y.abs, natOne)
715                         z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
716                         z.neg = true // z cannot be zero if x and y are negative
717                         return z
718                 }
719
720                 // x & y == x & y
721                 z.abs = z.abs.and(x.abs, y.abs)
722                 z.neg = false
723                 return z
724         }
725
726         // x.neg != y.neg
727         if x.neg {
728                 x, y = y, x // & is symmetric
729         }
730
731         // x & (-y) == x & ^(y-1) == x &^ (y-1)
732         y1 := nat(nil).sub(y.abs, natOne)
733         z.abs = z.abs.andNot(x.abs, y1)
734         z.neg = false
735         return z
736 }
737
738 // AndNot sets z = x &^ y and returns z.
739 func (z *Int) AndNot(x, y *Int) *Int {
740         if x.neg == y.neg {
741                 if x.neg {
742                         // (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
743                         x1 := nat(nil).sub(x.abs, natOne)
744                         y1 := nat(nil).sub(y.abs, natOne)
745                         z.abs = z.abs.andNot(y1, x1)
746                         z.neg = false
747                         return z
748                 }
749
750                 // x &^ y == x &^ y
751                 z.abs = z.abs.andNot(x.abs, y.abs)
752                 z.neg = false
753                 return z
754         }
755
756         if x.neg {
757                 // (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
758                 x1 := nat(nil).sub(x.abs, natOne)
759                 z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
760                 z.neg = true // z cannot be zero if x is negative and y is positive
761                 return z
762         }
763
764         // x &^ (-y) == x &^ ^(y-1) == x & (y-1)
765         y1 := nat(nil).add(y.abs, natOne)
766         z.abs = z.abs.and(x.abs, y1)
767         z.neg = false
768         return z
769 }
770
771 // Or sets z = x | y and returns z.
772 func (z *Int) Or(x, y *Int) *Int {
773         if x.neg == y.neg {
774                 if x.neg {
775                         // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
776                         x1 := nat(nil).sub(x.abs, natOne)
777                         y1 := nat(nil).sub(y.abs, natOne)
778                         z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
779                         z.neg = true // z cannot be zero if x and y are negative
780                         return z
781                 }
782
783                 // x | y == x | y
784                 z.abs = z.abs.or(x.abs, y.abs)
785                 z.neg = false
786                 return z
787         }
788
789         // x.neg != y.neg
790         if x.neg {
791                 x, y = y, x // | is symmetric
792         }
793
794         // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
795         y1 := nat(nil).sub(y.abs, natOne)
796         z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
797         z.neg = true // z cannot be zero if one of x or y is negative
798         return z
799 }
800
801 // Xor sets z = x ^ y and returns z.
802 func (z *Int) Xor(x, y *Int) *Int {
803         if x.neg == y.neg {
804                 if x.neg {
805                         // (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
806                         x1 := nat(nil).sub(x.abs, natOne)
807                         y1 := nat(nil).sub(y.abs, natOne)
808                         z.abs = z.abs.xor(x1, y1)
809                         z.neg = false
810                         return z
811                 }
812
813                 // x ^ y == x ^ y
814                 z.abs = z.abs.xor(x.abs, y.abs)
815                 z.neg = false
816                 return z
817         }
818
819         // x.neg != y.neg
820         if x.neg {
821                 x, y = y, x // ^ is symmetric
822         }
823
824         // x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
825         y1 := nat(nil).sub(y.abs, natOne)
826         z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
827         z.neg = true // z cannot be zero if only one of x or y is negative
828         return z
829 }
830
831 // Not sets z = ^x and returns z.
832 func (z *Int) Not(x *Int) *Int {
833         if x.neg {
834                 // ^(-x) == ^(^(x-1)) == x-1
835                 z.abs = z.abs.sub(x.abs, natOne)
836                 z.neg = false
837                 return z
838         }
839
840         // ^x == -x-1 == -(x+1)
841         z.abs = z.abs.add(x.abs, natOne)
842         z.neg = true // z cannot be zero if x is positive
843         return z
844 }
845
846 // Gob codec version. Permits backward-compatible changes to the encoding.
847 const intGobVersion byte = 1
848
849 // GobEncode implements the gob.GobEncoder interface.
850 func (z *Int) GobEncode() ([]byte, error) {
851         buf := make([]byte, 1+len(z.abs)*_S) // extra byte for version and sign bit
852         i := z.abs.bytes(buf) - 1            // i >= 0
853         b := intGobVersion << 1              // make space for sign bit
854         if z.neg {
855                 b |= 1
856         }
857         buf[i] = b
858         return buf[i:], nil
859 }
860
861 // GobDecode implements the gob.GobDecoder interface.
862 func (z *Int) GobDecode(buf []byte) error {
863         if len(buf) == 0 {
864                 return errors.New("Int.GobDecode: no data")
865         }
866         b := buf[0]
867         if b>>1 != intGobVersion {
868                 return errors.New(fmt.Sprintf("Int.GobDecode: encoding version %d not supported", b>>1))
869         }
870         z.neg = b&1 != 0
871         z.abs = z.abs.setBytes(buf[1:])
872         return nil
873 }