Commit b9caa4ac authored by Robert Griesemer's avatar Robert Griesemer

big: completed set of Int division routines & cleanups

- renamed Len -> BitLen, simplified implementation
- renamed old Div, Mod, DivMod -> Que, Rem, QuoRem
- implemented Div, Mod, DivMod (Euclidian definition, more
  useful in a mathematical context)
- fixed a bug in Exp (-0 was possible)
- added extra tests to check normalized results everywhere
- uniformly set Int.neg flag at the end of computations
- minor cosmetic cleanups
- ran all tests

R=rsc
CC=golang-dev
https://golang.org/cl/1091041
parent 32df6788
...@@ -14,8 +14,11 @@ type Int struct { ...@@ -14,8 +14,11 @@ type Int struct {
} }
// New allocates and returns a new Int set to x. var intOne = &Int{false, natOne}
func (z *Int) New(x int64) *Int {
// SetInt64 sets z to x and returns z.
func (z *Int) SetInt64(x int64) *Int {
z.neg = false z.neg = false
if x < 0 { if x < 0 {
z.neg = true z.neg = true
...@@ -27,7 +30,9 @@ func (z *Int) New(x int64) *Int { ...@@ -27,7 +30,9 @@ func (z *Int) New(x int64) *Int {
// NewInt allocates and returns a new Int set to x. // NewInt allocates and returns a new Int set to x.
func NewInt(x int64) *Int { return new(Int).New(x) } func NewInt(x int64) *Int {
return new(Int).SetInt64(x)
}
// Set sets z to x. // Set sets z to x.
...@@ -38,57 +43,51 @@ func (z *Int) Set(x *Int) *Int { ...@@ -38,57 +43,51 @@ func (z *Int) Set(x *Int) *Int {
} }
// Add computes z = x+y. // Add sets z to the sum x+y and returns z.
func (z *Int) Add(x, y *Int) *Int { func (z *Int) Add(x, y *Int) *Int {
neg := x.neg
if x.neg == y.neg { if x.neg == y.neg {
// x + y == x + y // x + y == x + y
// (-x) + (-y) == -(x + y) // (-x) + (-y) == -(x + y)
z.neg = x.neg
z.abs = z.abs.add(x.abs, y.abs) z.abs = z.abs.add(x.abs, y.abs)
} else { } else {
// x + (-y) == x - y == -(y - x) // x + (-y) == x - y == -(y - x)
// (-x) + y == y - x == -(x - y) // (-x) + y == y - x == -(x - y)
if x.abs.cmp(y.abs) >= 0 { if x.abs.cmp(y.abs) >= 0 {
z.neg = x.neg
z.abs = z.abs.sub(x.abs, y.abs) z.abs = z.abs.sub(x.abs, y.abs)
} else { } else {
z.neg = !x.neg neg = !neg
z.abs = z.abs.sub(y.abs, x.abs) z.abs = z.abs.sub(y.abs, x.abs)
} }
} }
if len(z.abs) == 0 { z.neg = len(z.abs) > 0 && neg // 0 has no sign
z.neg = false // 0 has no sign
}
return z return z
} }
// Sub computes z = x-y. // Sub sets z to the difference x-y and returns z.
func (z *Int) Sub(x, y *Int) *Int { func (z *Int) Sub(x, y *Int) *Int {
neg := x.neg
if x.neg != y.neg { if x.neg != y.neg {
// x - (-y) == x + y // x - (-y) == x + y
// (-x) - y == -(x + y) // (-x) - y == -(x + y)
z.neg = x.neg
z.abs = z.abs.add(x.abs, y.abs) z.abs = z.abs.add(x.abs, y.abs)
} else { } else {
// x - y == x - y == -(y - x) // x - y == x - y == -(y - x)
// (-x) - (-y) == y - x == -(x - y) // (-x) - (-y) == y - x == -(x - y)
if x.abs.cmp(y.abs) >= 0 { if x.abs.cmp(y.abs) >= 0 {
z.neg = x.neg
z.abs = z.abs.sub(x.abs, y.abs) z.abs = z.abs.sub(x.abs, y.abs)
} else { } else {
z.neg = !x.neg neg = !neg
z.abs = z.abs.sub(y.abs, x.abs) z.abs = z.abs.sub(y.abs, x.abs)
} }
} }
if len(z.abs) == 0 { z.neg = len(z.abs) > 0 && neg // 0 has no sign
z.neg = false // 0 has no sign
}
return z return z
} }
// Mul computes z = x*y. // Mul sets z to the product x*y and returns z.
func (z *Int) Mul(x, y *Int) *Int { func (z *Int) Mul(x, y *Int) *Int {
// x * y == x * y // x * y == x * y
// x * (-y) == -(x * y) // x * (-y) == -(x * y)
...@@ -100,38 +99,117 @@ func (z *Int) Mul(x, y *Int) *Int { ...@@ -100,38 +99,117 @@ func (z *Int) Mul(x, y *Int) *Int {
} }
// Div calculates q = (x-r)/y and sets z = q. // Quo sets z to the quotient x/y for y != 0 and returns z.
func (z *Int) Div(x, y *Int) *Int { // If y == 0, a division-by-zero run-time panic occurs.
r := new(Int) // See QuoRem for more details.
div(z, r, x, y) func (z *Int) Quo(x, y *Int) *Int {
z.abs, _ = z.abs.div(nil, x.abs, y.abs)
z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign
return z return z
} }
// Mod calculates q = (x-r)/y and sets z = r. // Rem sets z to the remainder x%y for y != 0 and returns z.
func (z *Int) Mod(x, y *Int) *Int { // If y == 0, a division-by-zero run-time panic occurs.
q := new(Int) // See QuoRem for more details.
div(q, z, x, y) func (z *Int) Rem(x, y *Int) *Int {
_, z.abs = nat(nil).div(z.abs, x.abs, y.abs)
z.neg = len(z.abs) > 0 && x.neg // 0 has no sign
return z return z
} }
// DivMod calculates q = (x-r)/y and sets z = q. (It returns z, r.) // QuoRem sets z to the quotient x/y and r to the remainder x%y
func (z *Int) DivMod(x, y, r *Int) (*Int, *Int) { // and returns the pair (z, r) for y != 0.
div(z, r, x, y) // If y == 0, a division-by-zero run-time panic occurs.
//
// QuoRem implements T-division and modulus (like Go):
//
// q = x/y with the result truncated to zero
// r = x - y*q
//
// (See Daan Leijen, ``Division and Modulus for Computer Scientists''.)
//
func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int) {
z.abs, r.abs = z.abs.div(r.abs, x.abs, y.abs)
z.neg, r.neg = len(z.abs) > 0 && x.neg != y.neg, len(r.abs) > 0 && x.neg // 0 has no sign
return z, r return z, r
} }
func div(q, r, x, y *Int) { // Div sets z to the quotient x/y for y != 0 and returns z.
q.neg = x.neg != y.neg // If y == 0, a division-by-zero run-time panic occurs.
r.neg = x.neg // See DivMod for more details.
q.abs, r.abs = q.abs.div(r.abs, x.abs, y.abs) func (z *Int) Div(x, y *Int) *Int {
return y_neg := y.neg // z may be an alias for y
var r Int
z.QuoRem(x, y, &r)
if r.neg {
if y_neg {
z.Add(z, intOne)
} else {
z.Sub(z, intOne)
}
}
return z
}
// Mod sets z to the modulus x%y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// See DivMod for more details.
func (z *Int) Mod(x, y *Int) *Int {
y0 := y // save y
if z == y || alias(z.abs, y.abs) {
y0 = new(Int).Set(y)
}
var q Int
q.QuoRem(x, y, z)
if z.neg {
if y0.neg {
z.Sub(z, y0)
} else {
z.Add(z, y0)
}
}
return z
}
// DivMod sets z to the quotient x div y and m to the modulus x mod y
// and returns the pair (z, m) for y != 0.
// If y == 0, a division-by-zero run-time panic occurs.
//
// DivMod implements Euclidian division and modulus (unlike Go):
//
// q = x div y such that
// m = x - y*q with 0 <= m < |q|
//
// (See Raymond T. Boute, ``The Euclidian definition of the functions
// div and mod''. ACM Transactions on Programming Languages and
// Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992.
// ACM press.)
//
func (z *Int) DivMod(x, y, m *Int) (*Int, *Int) {
y0 := y // save y
if z == y || alias(z.abs, y.abs) {
y0 = new(Int).Set(y)
}
z.QuoRem(x, y, m)
if m.neg {
if y0.neg {
z.Add(z, intOne)
m.Sub(m, y0)
} else {
z.Sub(z, intOne)
m.Add(m, y0)
}
}
return z, m
} }
// Neg computes z = -x. // Neg computes the negation z = -x.
func (z *Int) Neg(x *Int) *Int { func (z *Int) Neg(x *Int) *Int {
z.abs = z.abs.set(x.abs) z.abs = z.abs.set(x.abs)
z.neg = len(z.abs) > 0 && !x.neg // 0 has no sign z.neg = len(z.abs) > 0 && !x.neg // 0 has no sign
...@@ -139,7 +217,7 @@ func (z *Int) Neg(x *Int) *Int { ...@@ -139,7 +217,7 @@ func (z *Int) Neg(x *Int) *Int {
} }
// Cmp compares x and y. The result is // Cmp compares x and y and returns:
// //
// -1 if x < y // -1 if x < y
// 0 if x == y // 0 if x == y
...@@ -205,26 +283,23 @@ func (z *Int) SetString(s string, base int) (*Int, bool) { ...@@ -205,26 +283,23 @@ func (z *Int) SetString(s string, base int) (*Int, bool) {
goto Error goto Error
} }
neg := false
if s[0] == '-' { if s[0] == '-' {
z.neg = true neg = true
s = s[1:] s = s[1:]
} else {
z.neg = false
} }
z.abs, _, scanned = z.abs.scan(s, base) z.abs, _, scanned = z.abs.scan(s, base)
if scanned != len(s) { if scanned != len(s) {
goto Error goto Error
} }
if len(z.abs) == 0 { z.neg = len(z.abs) > 0 && neg // 0 has no sign
z.neg = false // 0 has no sign
}
return z, true return z, true
Error: Error:
z.neg = false
z.abs = nil z.abs = nil
z.neg = false
return z, false return z, false
} }
...@@ -234,7 +309,6 @@ Error: ...@@ -234,7 +309,6 @@ Error:
func (z *Int) SetBytes(b []byte) *Int { func (z *Int) SetBytes(b []byte) *Int {
s := int(_S) s := int(_S)
z.abs = z.abs.make((len(b) + s - 1) / s) z.abs = z.abs.make((len(b) + s - 1) / s)
z.neg = false
j := 0 j := 0
for len(b) >= s { for len(b) >= s {
...@@ -262,7 +336,7 @@ func (z *Int) SetBytes(b []byte) *Int { ...@@ -262,7 +336,7 @@ func (z *Int) SetBytes(b []byte) *Int {
} }
z.abs = z.abs.norm() z.abs = z.abs.norm()
z.neg = false
return z return z
} }
...@@ -289,14 +363,10 @@ func (z *Int) Bytes() []byte { ...@@ -289,14 +363,10 @@ func (z *Int) Bytes() []byte {
} }
// Len returns the length of the absolute value of z in bits. Zero is // BitLen returns the length of the absolute value of z in bits.
// considered to have a length of zero. // The bit length of 0 is 0.
func (z *Int) Len() int { func (z *Int) BitLen() int {
if len(z.abs) == 0 { return z.abs.bitLen()
return 0
}
return len(z.abs)*_W - int(leadingZeros(z.abs[len(z.abs)-1]))
} }
...@@ -304,7 +374,7 @@ func (z *Int) Len() int { ...@@ -304,7 +374,7 @@ func (z *Int) Len() int {
// See Knuth, volume 2, section 4.6.3. // See Knuth, volume 2, section 4.6.3.
func (z *Int) Exp(x, y, m *Int) *Int { func (z *Int) Exp(x, y, m *Int) *Int {
if y.neg || len(y.abs) == 0 { if y.neg || len(y.abs) == 0 {
z.New(1) z.SetInt64(1)
z.neg = x.neg z.neg = x.neg
return z return z
} }
...@@ -315,7 +385,7 @@ func (z *Int) Exp(x, y, m *Int) *Int { ...@@ -315,7 +385,7 @@ func (z *Int) Exp(x, y, m *Int) *Int {
} }
z.abs = z.abs.expNN(x.abs, y.abs, mWords) z.abs = z.abs.expNN(x.abs, y.abs, mWords)
z.neg = x.neg && y.abs[0]&1 == 1 z.neg = len(z.abs) > 0 && x.neg && y.abs[0]&1 == 1 // 0 has no sign
return z return z
} }
...@@ -326,12 +396,12 @@ func (z *Int) Exp(x, y, m *Int) *Int { ...@@ -326,12 +396,12 @@ func (z *Int) Exp(x, y, m *Int) *Int {
// If either a or b is not positive, GcdInt sets d = x = y = 0. // If either a or b is not positive, GcdInt sets d = x = y = 0.
func GcdInt(d, x, y, a, b *Int) { func GcdInt(d, x, y, a, b *Int) {
if a.neg || b.neg { if a.neg || b.neg {
d.New(0) d.SetInt64(0)
if x != nil { if x != nil {
x.New(0) x.SetInt64(0)
} }
if y != nil { if y != nil {
y.New(0) y.SetInt64(0)
} }
return return
} }
...@@ -340,9 +410,9 @@ func GcdInt(d, x, y, a, b *Int) { ...@@ -340,9 +410,9 @@ func GcdInt(d, x, y, a, b *Int) {
B := new(Int).Set(b) B := new(Int).Set(b)
X := new(Int) X := new(Int)
Y := new(Int).New(1) Y := new(Int).SetInt64(1)
lastX := new(Int).New(1) lastX := new(Int).SetInt64(1)
lastY := new(Int) lastY := new(Int)
q := new(Int) q := new(Int)
...@@ -350,7 +420,7 @@ func GcdInt(d, x, y, a, b *Int) { ...@@ -350,7 +420,7 @@ func GcdInt(d, x, y, a, b *Int) {
for len(B.abs) > 0 { for len(B.abs) > 0 {
r := new(Int) r := new(Int)
q, r = q.DivMod(A, B, r) q, r = q.QuoRem(A, B, r)
A, B = B, r A, B = B, r
...@@ -382,13 +452,15 @@ func GcdInt(d, x, y, a, b *Int) { ...@@ -382,13 +452,15 @@ func GcdInt(d, x, y, a, b *Int) {
// ProbablyPrime performs n Miller-Rabin tests to check whether z is prime. // ProbablyPrime performs n Miller-Rabin tests to check whether z is prime.
// If it returns true, z is prime with probability 1 - 1/4^n. // If it returns true, z is prime with probability 1 - 1/4^n.
// If it returns false, z is not prime. // If it returns false, z is not prime.
func ProbablyPrime(z *Int, n int) bool { return !z.neg && z.abs.probablyPrime(n) } func ProbablyPrime(z *Int, n int) bool {
return !z.neg && z.abs.probablyPrime(n)
}
// Lsh sets z = x << n and returns z. // Lsh sets z = x << n and returns z.
func (z *Int) Lsh(x *Int, n uint) *Int { func (z *Int) Lsh(x *Int, n uint) *Int {
z.neg = x.neg
z.abs = z.abs.shl(x.abs, n) z.abs = z.abs.shl(x.abs, n)
z.neg = x.neg
return z return z
} }
...@@ -397,18 +469,19 @@ func (z *Int) Lsh(x *Int, n uint) *Int { ...@@ -397,18 +469,19 @@ func (z *Int) Lsh(x *Int, n uint) *Int {
func (z *Int) Rsh(x *Int, n uint) *Int { func (z *Int) Rsh(x *Int, n uint) *Int {
if x.neg { if x.neg {
// (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1) // (-x) >> s == ^(x-1) >> s == ^((x-1) >> s) == -(((x-1) >> s) + 1)
z.neg = true
t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0 t := z.abs.sub(x.abs, natOne) // no underflow because |x| > 0
t = t.shr(t, n) t = t.shr(t, n)
z.abs = t.add(t, natOne) z.abs = t.add(t, natOne)
z.neg = true // z cannot be zero if x is negative
return z return z
} }
z.neg = false
z.abs = z.abs.shr(x.abs, n) z.abs = z.abs.shr(x.abs, n)
z.neg = false
return z return z
} }
// And sets z = x & y and returns z. // And sets z = x & y and returns z.
func (z *Int) And(x, y *Int) *Int { func (z *Int) And(x, y *Int) *Int {
if x.neg == y.neg { if x.neg == y.neg {
...@@ -416,14 +489,14 @@ func (z *Int) And(x, y *Int) *Int { ...@@ -416,14 +489,14 @@ func (z *Int) And(x, y *Int) *Int {
// (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1) // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1)
x1 := nat{}.sub(x.abs, natOne) x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne) y1 := z.abs.sub(y.abs, natOne)
z.neg = true
z.abs = z.abs.add(z.abs.or(x1, y1), natOne) z.abs = z.abs.add(z.abs.or(x1, y1), natOne)
z.neg = true // z cannot be zero if x and y are negative
return z return z
} }
// x & y == x & y // x & y == x & y
z.neg = false
z.abs = z.abs.and(x.abs, y.abs) z.abs = z.abs.and(x.abs, y.abs)
z.neg = false
return z return z
} }
...@@ -434,8 +507,8 @@ func (z *Int) And(x, y *Int) *Int { ...@@ -434,8 +507,8 @@ func (z *Int) And(x, y *Int) *Int {
// x & (-y) == x & ^(y-1) == x &^ (y-1) // x & (-y) == x & ^(y-1) == x &^ (y-1)
y1 := z.abs.sub(y.abs, natOne) y1 := z.abs.sub(y.abs, natOne)
z.neg = false
z.abs = z.abs.andNot(x.abs, y1) z.abs = z.abs.andNot(x.abs, y1)
z.neg = false
return z return z
} }
...@@ -447,29 +520,29 @@ func (z *Int) AndNot(x, y *Int) *Int { ...@@ -447,29 +520,29 @@ func (z *Int) AndNot(x, y *Int) *Int {
// (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1) // (-x) &^ (-y) == ^(x-1) &^ ^(y-1) == ^(x-1) & (y-1) == (y-1) &^ (x-1)
x1 := nat{}.sub(x.abs, natOne) x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne) y1 := z.abs.sub(y.abs, natOne)
z.neg = false
z.abs = z.abs.andNot(y1, x1) z.abs = z.abs.andNot(y1, x1)
z.neg = false
return z return z
} }
// x &^ y == x &^ y // x &^ y == x &^ y
z.neg = false
z.abs = z.abs.andNot(x.abs, y.abs) z.abs = z.abs.andNot(x.abs, y.abs)
z.neg = false
return z return z
} }
if x.neg { if x.neg {
// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1) // (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
x1 := z.abs.sub(x.abs, natOne) x1 := z.abs.sub(x.abs, natOne)
z.neg = true
z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne) z.abs = z.abs.add(z.abs.or(x1, y.abs), natOne)
z.neg = true // z cannot be zero if x is negative and y is positive
return z return z
} }
// x &^ (-y) == x &^ ^(y-1) == x & (y-1) // x &^ (-y) == x &^ ^(y-1) == x & (y-1)
y1 := z.abs.add(y.abs, natOne) y1 := z.abs.add(y.abs, natOne)
z.neg = false
z.abs = z.abs.and(x.abs, y1) z.abs = z.abs.and(x.abs, y1)
z.neg = false
return z return z
} }
...@@ -481,14 +554,14 @@ func (z *Int) Or(x, y *Int) *Int { ...@@ -481,14 +554,14 @@ func (z *Int) Or(x, y *Int) *Int {
// (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1) // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1)
x1 := nat{}.sub(x.abs, natOne) x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne) y1 := z.abs.sub(y.abs, natOne)
z.neg = true
z.abs = z.abs.add(z.abs.and(x1, y1), natOne) z.abs = z.abs.add(z.abs.and(x1, y1), natOne)
z.neg = true // z cannot be zero if x and y are negative
return z return z
} }
// x | y == x | y // x | y == x | y
z.neg = false
z.abs = z.abs.or(x.abs, y.abs) z.abs = z.abs.or(x.abs, y.abs)
z.neg = false
return z return z
} }
...@@ -499,8 +572,8 @@ func (z *Int) Or(x, y *Int) *Int { ...@@ -499,8 +572,8 @@ func (z *Int) Or(x, y *Int) *Int {
// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1) // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
y1 := z.abs.sub(y.abs, natOne) y1 := z.abs.sub(y.abs, natOne)
z.neg = true
z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne) z.abs = z.abs.add(z.abs.andNot(y1, x.abs), natOne)
z.neg = true // z cannot be zero if one of x or y is negative
return z return z
} }
...@@ -512,26 +585,26 @@ func (z *Int) Xor(x, y *Int) *Int { ...@@ -512,26 +585,26 @@ func (z *Int) Xor(x, y *Int) *Int {
// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1) // (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
x1 := nat{}.sub(x.abs, natOne) x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne) y1 := z.abs.sub(y.abs, natOne)
z.neg = false
z.abs = z.abs.xor(x1, y1) z.abs = z.abs.xor(x1, y1)
z.neg = false
return z return z
} }
// x ^ y == x ^ y // x ^ y == x ^ y
z.neg = false
z.abs = z.abs.xor(x.abs, y.abs) z.abs = z.abs.xor(x.abs, y.abs)
z.neg = false
return z return z
} }
// x.neg != y.neg // x.neg != y.neg
if x.neg { if x.neg {
x, y = y, x // | is symmetric x, y = y, x // ^ is symmetric
} }
// x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1) // x ^ (-y) == x ^ ^(y-1) == ^(x ^ (y-1)) == -((x ^ (y-1)) + 1)
y1 := z.abs.sub(y.abs, natOne) y1 := z.abs.sub(y.abs, natOne)
z.neg = true
z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne) z.abs = z.abs.add(z.abs.xor(x.abs, y1), natOne)
z.neg = true // z cannot be zero if only one of x or y is negative
return z return z
} }
...@@ -540,13 +613,13 @@ func (z *Int) Xor(x, y *Int) *Int { ...@@ -540,13 +613,13 @@ func (z *Int) Xor(x, y *Int) *Int {
func (z *Int) Not(x *Int) *Int { func (z *Int) Not(x *Int) *Int {
if x.neg { if x.neg {
// ^(-x) == ^(^(x-1)) == x-1 // ^(-x) == ^(^(x-1)) == x-1
z.neg = false
z.abs = z.abs.sub(x.abs, natOne) z.abs = z.abs.sub(x.abs, natOne)
z.neg = false
return z return z
} }
// ^x == -x-1 == -(x+1) // ^x == -x-1 == -(x+1)
z.neg = true
z.abs = z.abs.add(x.abs, natOne) z.abs = z.abs.add(x.abs, natOne)
z.neg = true // z cannot be zero if x is positive
return z return z
} }
...@@ -11,9 +11,13 @@ import ( ...@@ -11,9 +11,13 @@ import (
"testing/quick" "testing/quick"
) )
func newZ(x int64) *Int {
var z Int func isNormalized(x *Int) bool {
return z.New(x) if len(x.abs) == 0 {
return !x.neg
}
// len(x.abs) > 0
return x.abs[len(x.abs)-1] != 0
} }
...@@ -24,20 +28,20 @@ type argZZ struct { ...@@ -24,20 +28,20 @@ type argZZ struct {
var sumZZ = []argZZ{ var sumZZ = []argZZ{
argZZ{newZ(0), newZ(0), newZ(0)}, argZZ{NewInt(0), NewInt(0), NewInt(0)},
argZZ{newZ(1), newZ(1), newZ(0)}, argZZ{NewInt(1), NewInt(1), NewInt(0)},
argZZ{newZ(1111111110), newZ(123456789), newZ(987654321)}, argZZ{NewInt(1111111110), NewInt(123456789), NewInt(987654321)},
argZZ{newZ(-1), newZ(-1), newZ(0)}, argZZ{NewInt(-1), NewInt(-1), NewInt(0)},
argZZ{newZ(864197532), newZ(-123456789), newZ(987654321)}, argZZ{NewInt(864197532), NewInt(-123456789), NewInt(987654321)},
argZZ{newZ(-1111111110), newZ(-123456789), newZ(-987654321)}, argZZ{NewInt(-1111111110), NewInt(-123456789), NewInt(-987654321)},
} }
var prodZZ = []argZZ{ var prodZZ = []argZZ{
argZZ{newZ(0), newZ(0), newZ(0)}, argZZ{NewInt(0), NewInt(0), NewInt(0)},
argZZ{newZ(0), newZ(1), newZ(0)}, argZZ{NewInt(0), NewInt(1), NewInt(0)},
argZZ{newZ(1), newZ(1), newZ(1)}, argZZ{NewInt(1), NewInt(1), NewInt(1)},
argZZ{newZ(-991 * 991), newZ(991), newZ(-991)}, argZZ{NewInt(-991 * 991), NewInt(991), NewInt(-991)},
// TODO(gri) add larger products // TODO(gri) add larger products
} }
...@@ -46,6 +50,9 @@ func TestSetZ(t *testing.T) { ...@@ -46,6 +50,9 @@ func TestSetZ(t *testing.T) {
for _, a := range sumZZ { for _, a := range sumZZ {
var z Int var z Int
z.Set(a.z) z.Set(a.z)
if !isNormalized(&z) {
t.Errorf("%v is not normalized", z)
}
if (&z).Cmp(a.z) != 0 { if (&z).Cmp(a.z) != 0 {
t.Errorf("got z = %v; want %v", z, a.z) t.Errorf("got z = %v; want %v", z, a.z)
} }
...@@ -56,6 +63,9 @@ func TestSetZ(t *testing.T) { ...@@ -56,6 +63,9 @@ func TestSetZ(t *testing.T) {
func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) { func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) {
var z Int var z Int
f(&z, a.x, a.y) f(&z, a.x, a.y)
if !isNormalized(&z) {
t.Errorf("msg: %v is not normalized", z, msg)
}
if (&z).Cmp(a.z) != 0 { if (&z).Cmp(a.z) != 0 {
t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z) t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z)
} }
...@@ -186,7 +196,7 @@ func TestSetString(t *testing.T) { ...@@ -186,7 +196,7 @@ func TestSetString(t *testing.T) {
for i, test := range fromStringTests { for i, test := range fromStringTests {
n1, ok1 := new(Int).SetString(test.in, test.base) n1, ok1 := new(Int).SetString(test.in, test.base)
n2, ok2 := n2.SetString(test.in, test.base) n2, ok2 := n2.SetString(test.in, test.base)
expected := new(Int).New(test.out) expected := NewInt(test.out)
if ok1 != test.ok || ok2 != test.ok { if ok1 != test.ok || ok2 != test.ok {
t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok) t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok)
continue continue
...@@ -195,6 +205,13 @@ func TestSetString(t *testing.T) { ...@@ -195,6 +205,13 @@ func TestSetString(t *testing.T) {
continue continue
} }
if ok1 && !isNormalized(n1) {
t.Errorf("#%d (input '%s'): %v is not normalized", i, test.in, *n1)
}
if ok2 && !isNormalized(n2) {
t.Errorf("#%d (input '%s'): %v is not normalized", i, test.in, *n2)
}
if n1.Cmp(expected) != 0 { if n1.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d\n", i, test.in, n1, test.out) t.Errorf("#%d (input '%s') got: %s want: %d\n", i, test.in, n1, test.out)
} }
...@@ -205,33 +222,77 @@ func TestSetString(t *testing.T) { ...@@ -205,33 +222,77 @@ func TestSetString(t *testing.T) {
} }
type divSignsTest struct { type divisionSignsTest struct {
x, y int64 x, y int64
q, r int64 q, r int64 // T-division
d, m int64 // Euclidian division
} }
// These examples taken from the Go Language Spec, section "Arithmetic operators" // Examples from the Go Language Spec, section "Arithmetic operators"
var divSignsTests = []divSignsTest{ var divisionSignsTests = []divisionSignsTest{
divSignsTest{5, 3, 1, 2}, divisionSignsTest{5, 3, 1, 2, 1, 2},
divSignsTest{-5, 3, -1, -2}, divisionSignsTest{-5, 3, -1, -2, -2, 1},
divSignsTest{5, -3, -1, 2}, divisionSignsTest{5, -3, -1, 2, -1, 2},
divSignsTest{-5, -3, 1, -2}, divisionSignsTest{-5, -3, 1, -2, 2, 1},
divSignsTest{1, 2, 0, 1}, divisionSignsTest{1, 2, 0, 1, 0, 1},
divisionSignsTest{8, 4, 2, 0, 2, 0},
} }
func TestDivSigns(t *testing.T) { func TestDivisionSigns(t *testing.T) {
for i, test := range divSignsTests { for i, test := range divisionSignsTests {
x := new(Int).New(test.x) x := NewInt(test.x)
y := new(Int).New(test.y) y := NewInt(test.y)
r := new(Int) q := NewInt(test.q)
q, r := new(Int).DivMod(x, y, r) r := NewInt(test.r)
expectedQ := new(Int).New(test.q) d := NewInt(test.d)
expectedR := new(Int).New(test.r) m := NewInt(test.m)
if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 { q1 := new(Int).Quo(x, y)
t.Errorf("#%d: got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR) r1 := new(Int).Rem(x, y)
if !isNormalized(q1) {
t.Errorf("#%d Quo: %v is not normalized", i, *q1)
}
if !isNormalized(r1) {
t.Errorf("#%d Rem: %v is not normalized", i, *r1)
}
if q1.Cmp(q) != 0 || r1.Cmp(r) != 0 {
t.Errorf("#%d QuoRem: got (%s, %s), want (%s, %s)", i, q1, r1, q, r)
}
q2, r2 := new(Int).QuoRem(x, y, new(Int))
if !isNormalized(q2) {
t.Errorf("#%d Quo: %v is not normalized", i, *q2)
}
if !isNormalized(r2) {
t.Errorf("#%d Rem: %v is not normalized", i, *r2)
}
if q2.Cmp(q) != 0 || r2.Cmp(r) != 0 {
t.Errorf("#%d QuoRem: got (%s, %s), want (%s, %s)", i, q2, r2, q, r)
}
d1 := new(Int).Div(x, y)
m1 := new(Int).Mod(x, y)
if !isNormalized(d1) {
t.Errorf("#%d Div: %v is not normalized", i, *d1)
}
if !isNormalized(m1) {
t.Errorf("#%d Mod: %v is not normalized", i, *m1)
}
if d1.Cmp(d) != 0 || m1.Cmp(m) != 0 {
t.Errorf("#%d DivMod: got (%s, %s), want (%s, %s)", i, d1, m1, d, m)
}
d2, m2 := new(Int).DivMod(x, y, new(Int))
if !isNormalized(d2) {
t.Errorf("#%d Div: %v is not normalized", i, *d2)
}
if !isNormalized(m2) {
t.Errorf("#%d Mod: %v is not normalized", i, *m2)
}
if d2.Cmp(d) != 0 || m2.Cmp(m) != 0 {
t.Errorf("#%d DivMod: got (%s, %s), want (%s, %s)", i, d2, m2, d, m)
} }
} }
} }
...@@ -273,7 +334,7 @@ func TestBytes(t *testing.T) { ...@@ -273,7 +334,7 @@ func TestBytes(t *testing.T) {
} }
func checkDiv(x, y []byte) bool { func checkQuo(x, y []byte) bool {
u := new(Int).SetBytes(x) u := new(Int).SetBytes(x)
v := new(Int).SetBytes(y) v := new(Int).SetBytes(y)
...@@ -282,7 +343,7 @@ func checkDiv(x, y []byte) bool { ...@@ -282,7 +343,7 @@ func checkDiv(x, y []byte) bool {
} }
r := new(Int) r := new(Int)
q, r := new(Int).DivMod(u, v, r) q, r := new(Int).QuoRem(u, v, r)
if r.Cmp(v) >= 0 { if r.Cmp(v) >= 0 {
return false return false
...@@ -296,20 +357,20 @@ func checkDiv(x, y []byte) bool { ...@@ -296,20 +357,20 @@ func checkDiv(x, y []byte) bool {
} }
type divTest struct { type quoTest struct {
x, y string x, y string
q, r string q, r string
} }
var divTests = []divTest{ var quoTests = []quoTest{
divTest{ quoTest{
"476217953993950760840509444250624797097991362735329973741718102894495832294430498335824897858659711275234906400899559094370964723884706254265559534144986498357", "476217953993950760840509444250624797097991362735329973741718102894495832294430498335824897858659711275234906400899559094370964723884706254265559534144986498357",
"9353930466774385905609975137998169297361893554149986716853295022578535724979483772383667534691121982974895531435241089241440253066816724367338287092081996", "9353930466774385905609975137998169297361893554149986716853295022578535724979483772383667534691121982974895531435241089241440253066816724367338287092081996",
"50911", "50911",
"1", "1",
}, },
divTest{ quoTest{
"11510768301994997771168", "11510768301994997771168",
"1328165573307167369775", "1328165573307167369775",
"8", "8",
...@@ -318,19 +379,19 @@ var divTests = []divTest{ ...@@ -318,19 +379,19 @@ var divTests = []divTest{
} }
func TestDiv(t *testing.T) { func TestQuo(t *testing.T) {
if err := quick.Check(checkDiv, nil); err != nil { if err := quick.Check(checkQuo, nil); err != nil {
t.Error(err) t.Error(err)
} }
for i, test := range divTests { for i, test := range quoTests {
x, _ := new(Int).SetString(test.x, 10) x, _ := new(Int).SetString(test.x, 10)
y, _ := new(Int).SetString(test.y, 10) y, _ := new(Int).SetString(test.y, 10)
expectedQ, _ := new(Int).SetString(test.q, 10) expectedQ, _ := new(Int).SetString(test.q, 10)
expectedR, _ := new(Int).SetString(test.r, 10) expectedR, _ := new(Int).SetString(test.r, 10)
r := new(Int) r := new(Int)
q, r := new(Int).DivMod(x, y, r) q, r := new(Int).QuoRem(x, y, r)
if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 { if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 {
t.Errorf("#%d got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR) t.Errorf("#%d got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR)
...@@ -339,7 +400,7 @@ func TestDiv(t *testing.T) { ...@@ -339,7 +400,7 @@ func TestDiv(t *testing.T) {
} }
func TestDivStepD6(t *testing.T) { func TestQuoStepD6(t *testing.T) {
// See Knuth, Volume 2, section 4.3.1, exercise 21. This code exercises // See Knuth, Volume 2, section 4.3.1, exercise 21. This code exercises
// a code path which only triggers 1 in 10^{-19} cases. // a code path which only triggers 1 in 10^{-19} cases.
...@@ -347,7 +408,7 @@ func TestDivStepD6(t *testing.T) { ...@@ -347,7 +408,7 @@ func TestDivStepD6(t *testing.T) {
v := &Int{false, nat{5, 2 + 1<<(_W-1), 1 << (_W - 1)}} v := &Int{false, nat{5, 2 + 1<<(_W-1), 1 << (_W - 1)}}
r := new(Int) r := new(Int)
q, r := new(Int).DivMod(u, v, r) q, r := new(Int).QuoRem(u, v, r)
const expectedQ64 = "18446744073709551613" const expectedQ64 = "18446744073709551613"
const expectedR64 = "3138550867693340382088035895064302439801311770021610913807" const expectedR64 = "3138550867693340382088035895064302439801311770021610913807"
const expectedQ32 = "4294967293" const expectedQ32 = "4294967293"
...@@ -359,35 +420,38 @@ func TestDivStepD6(t *testing.T) { ...@@ -359,35 +420,38 @@ func TestDivStepD6(t *testing.T) {
} }
type lenTest struct { type bitLenTest struct {
in string in string
out int out int
} }
var lenTests = []lenTest{ var bitLenTests = []bitLenTest{
lenTest{"0", 0}, bitLenTest{"-1", 1},
lenTest{"1", 1}, bitLenTest{"0", 0},
lenTest{"2", 2}, bitLenTest{"1", 1},
lenTest{"4", 3}, bitLenTest{"2", 2},
lenTest{"0x8000", 16}, bitLenTest{"4", 3},
lenTest{"0x80000000", 32}, bitLenTest{"0xabc", 12},
lenTest{"0x800000000000", 48}, bitLenTest{"0x8000", 16},
lenTest{"0x8000000000000000", 64}, bitLenTest{"0x80000000", 32},
lenTest{"0x80000000000000000000", 80}, bitLenTest{"0x800000000000", 48},
bitLenTest{"0x8000000000000000", 64},
bitLenTest{"0x80000000000000000000", 80},
bitLenTest{"-0x4000000000000000000000", 87},
} }
func TestLen(t *testing.T) { func TestBitLen(t *testing.T) {
for i, test := range lenTests { for i, test := range bitLenTests {
n, ok := new(Int).SetString(test.in, 0) x, ok := new(Int).SetString(test.in, 0)
if !ok { if !ok {
t.Errorf("#%d test input invalid: %s", i, test.in) t.Errorf("#%d test input invalid: %s", i, test.in)
continue continue
} }
if n.Len() != test.out { if n := x.BitLen(); n != test.out {
t.Errorf("#%d got %d want %d\n", i, n.Len(), test.out) t.Errorf("#%d got %d want %d\n", i, n, test.out)
} }
} }
} }
...@@ -404,6 +468,7 @@ var expTests = []expTest{ ...@@ -404,6 +468,7 @@ var expTests = []expTest{
expTest{"-5", "0", "", "-1"}, expTest{"-5", "0", "", "-1"},
expTest{"5", "1", "", "5"}, expTest{"5", "1", "", "5"},
expTest{"-5", "1", "", "-5"}, expTest{"-5", "1", "", "-5"},
expTest{"-2", "3", "2", "0"},
expTest{"5", "2", "", "25"}, expTest{"5", "2", "", "25"},
expTest{"1", "65537", "2", "1"}, expTest{"1", "65537", "2", "1"},
expTest{"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"}, expTest{"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"},
...@@ -436,13 +501,16 @@ func TestExp(t *testing.T) { ...@@ -436,13 +501,16 @@ func TestExp(t *testing.T) {
} }
if !ok1 || !ok2 || !ok3 || !ok4 { if !ok1 || !ok2 || !ok3 || !ok4 {
t.Errorf("#%d error in input", i) t.Errorf("#%d: error in input", i)
continue continue
} }
z := new(Int).Exp(x, y, m) z := new(Int).Exp(x, y, m)
if !isNormalized(z) {
t.Errorf("#%d: %v is not normalized", i, *z)
}
if z.Cmp(out) != 0 { if z.Cmp(out) != 0 {
t.Errorf("#%d got %s want %s", i, z, out) t.Errorf("#%d: got %s want %s", i, z, out)
} }
} }
} }
...@@ -478,16 +546,16 @@ var gcdTests = []gcdTest{ ...@@ -478,16 +546,16 @@ var gcdTests = []gcdTest{
func TestGcd(t *testing.T) { func TestGcd(t *testing.T) {
for i, test := range gcdTests { for i, test := range gcdTests {
a := new(Int).New(test.a) a := NewInt(test.a)
b := new(Int).New(test.b) b := NewInt(test.b)
x := new(Int) x := new(Int)
y := new(Int) y := new(Int)
d := new(Int) d := new(Int)
expectedX := new(Int).New(test.x) expectedX := NewInt(test.x)
expectedY := new(Int).New(test.y) expectedY := NewInt(test.y)
expectedD := new(Int).New(test.d) expectedD := NewInt(test.d)
GcdInt(d, x, y, a, b) GcdInt(d, x, y, a, b)
...@@ -594,8 +662,11 @@ func TestRsh(t *testing.T) { ...@@ -594,8 +662,11 @@ func TestRsh(t *testing.T) {
expected, _ := new(Int).SetString(test.out, 10) expected, _ := new(Int).SetString(test.out, 10)
out := new(Int).Rsh(in, test.shift) out := new(Int).Rsh(in, test.shift)
if !isNormalized(out) {
t.Errorf("#%d: %v is not normalized", i, *out)
}
if out.Cmp(expected) != 0 { if out.Cmp(expected) != 0 {
t.Errorf("#%d got %s want %s", i, out, expected) t.Errorf("#%d: got %s want %s", i, out, expected)
} }
} }
} }
...@@ -607,8 +678,11 @@ func TestRshSelf(t *testing.T) { ...@@ -607,8 +678,11 @@ func TestRshSelf(t *testing.T) {
expected, _ := new(Int).SetString(test.out, 10) expected, _ := new(Int).SetString(test.out, 10)
z.Rsh(z, test.shift) z.Rsh(z, test.shift)
if !isNormalized(z) {
t.Errorf("#%d: %v is not normalized", i, *z)
}
if z.Cmp(expected) != 0 { if z.Cmp(expected) != 0 {
t.Errorf("#%d got %s want %s", i, z, expected) t.Errorf("#%d: got %s want %s", i, z, expected)
} }
} }
} }
...@@ -643,8 +717,11 @@ func TestLsh(t *testing.T) { ...@@ -643,8 +717,11 @@ func TestLsh(t *testing.T) {
expected, _ := new(Int).SetString(test.out, 10) expected, _ := new(Int).SetString(test.out, 10)
out := new(Int).Lsh(in, test.shift) out := new(Int).Lsh(in, test.shift)
if !isNormalized(out) {
t.Errorf("#%d: %v is not normalized", i, *out)
}
if out.Cmp(expected) != 0 { if out.Cmp(expected) != 0 {
t.Errorf("#%d got %s want %s", i, out, expected) t.Errorf("#%d: got %s want %s", i, out, expected)
} }
} }
} }
...@@ -656,8 +733,11 @@ func TestLshSelf(t *testing.T) { ...@@ -656,8 +733,11 @@ func TestLshSelf(t *testing.T) {
expected, _ := new(Int).SetString(test.out, 10) expected, _ := new(Int).SetString(test.out, 10)
z.Lsh(z, test.shift) z.Lsh(z, test.shift)
if !isNormalized(z) {
t.Errorf("#%d: %v is not normalized", i, *z)
}
if z.Cmp(expected) != 0 { if z.Cmp(expected) != 0 {
t.Errorf("#%d got %s want %s", i, z, expected) t.Errorf("#%d: got %s want %s", i, z, expected)
} }
} }
} }
...@@ -669,8 +749,11 @@ func TestLshRsh(t *testing.T) { ...@@ -669,8 +749,11 @@ func TestLshRsh(t *testing.T) {
out := new(Int).Lsh(in, test.shift) out := new(Int).Lsh(in, test.shift)
out = out.Rsh(out, test.shift) out = out.Rsh(out, test.shift)
if !isNormalized(out) {
t.Errorf("#%d: %v is not normalized", i, *out)
}
if in.Cmp(out) != 0 { if in.Cmp(out) != 0 {
t.Errorf("#%d got %s want %s", i, out, in) t.Errorf("#%d: got %s want %s", i, out, in)
} }
} }
for i, test := range lshTests { for i, test := range lshTests {
...@@ -678,8 +761,11 @@ func TestLshRsh(t *testing.T) { ...@@ -678,8 +761,11 @@ func TestLshRsh(t *testing.T) {
out := new(Int).Lsh(in, test.shift) out := new(Int).Lsh(in, test.shift)
out.Rsh(out, test.shift) out.Rsh(out, test.shift)
if !isNormalized(out) {
t.Errorf("#%d: %v is not normalized", i, *out)
}
if in.Cmp(out) != 0 { if in.Cmp(out) != 0 {
t.Errorf("#%d got %s want %s", i, out, in) t.Errorf("#%d: got %s want %s", i, out, in)
} }
} }
} }
...@@ -721,6 +807,7 @@ var bitwiseTests = []bitwiseTest{ ...@@ -721,6 +807,7 @@ var bitwiseTests = []bitwiseTest{
bitwiseTest{"0x00", "0x01", "0x00", "0x01", "0x01", "0x00"}, bitwiseTest{"0x00", "0x01", "0x00", "0x01", "0x01", "0x00"},
bitwiseTest{"0x01", "0x00", "0x00", "0x01", "0x01", "0x01"}, bitwiseTest{"0x01", "0x00", "0x00", "0x01", "0x01", "0x01"},
bitwiseTest{"-0x01", "0x00", "0x00", "-0x01", "-0x01", "-0x01"}, bitwiseTest{"-0x01", "0x00", "0x00", "-0x01", "-0x01", "-0x01"},
bitwiseTest{"-0xAF", "-0x50", "0x00", "-0xFF", "-0x01", "-0x01"},
bitwiseTest{"0x00", "-0x01", "0x00", "-0x01", "-0x01", "0x00"}, bitwiseTest{"0x00", "-0x01", "0x00", "-0x01", "-0x01", "0x00"},
bitwiseTest{"0x01", "0x01", "0x01", "0x01", "0x00", "0x00"}, bitwiseTest{"0x01", "0x01", "0x01", "0x01", "0x00", "0x00"},
bitwiseTest{"-0x01", "-0x01", "-0x01", "-0x01", "0x00", "0x00"}, bitwiseTest{"-0x01", "-0x01", "-0x01", "-0x01", "0x00", "0x00"},
......
...@@ -356,7 +356,7 @@ func karatsuba(z, x, y nat) { ...@@ -356,7 +356,7 @@ func karatsuba(z, x, y nat) {
// alias returns true if x and y share the same base array. // alias returns true if x and y share the same base array.
func alias(x, y nat) bool { func alias(x, y nat) bool {
return &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1] return cap(x) > 0 && cap(y) > 0 && &x[0:cap(x)][cap(x)-1] == &y[0:cap(y)][cap(y)-1]
} }
...@@ -412,7 +412,7 @@ func (z nat) mul(x, y nat) nat { ...@@ -412,7 +412,7 @@ func (z nat) mul(x, y nat) nat {
// m >= n > 1 // m >= n > 1
// determine if z can be reused // determine if z can be reused
if len(z) > 0 && (alias(z, x) || alias(z, y)) { if alias(z, x) || alias(z, y) {
z = nil // z is an alias for x or y - cannot reuse z = nil // z is an alias for x or y - cannot reuse
} }
...@@ -757,7 +757,7 @@ func (z nat) shl(x nat, s uint) nat { ...@@ -757,7 +757,7 @@ func (z nat) shl(x nat, s uint) nat {
// determine if z can be reused // determine if z can be reused
// TODO(gri) change shlVW so we don't need this // TODO(gri) change shlVW so we don't need this
if len(z) > 0 && alias(z, x) { if alias(z, x) {
z = nil // z is an alias for x - cannot reuse z = nil // z is an alias for x - cannot reuse
} }
...@@ -780,7 +780,7 @@ func (z nat) shr(x nat, s uint) nat { ...@@ -780,7 +780,7 @@ func (z nat) shr(x nat, s uint) nat {
// determine if z can be reused // determine if z can be reused
// TODO(gri) change shrVW so we don't need this // TODO(gri) change shrVW so we don't need this
if len(z) > 0 && alias(z, x) { if alias(z, x) {
z = nil // z is an alias for x - cannot reuse z = nil // z is an alias for x - cannot reuse
} }
......
...@@ -253,7 +253,7 @@ func (x *Integer) QuoRem(y *Integer) (*Integer, *Integer) { ...@@ -253,7 +253,7 @@ func (x *Integer) QuoRem(y *Integer) (*Integer, *Integer) {
// Div and Mod implement Euclidian division and modulus: // Div and Mod implement Euclidian division and modulus:
// //
// q = x.Div(y) // q = x.Div(y)
// r = x.Mod(y) with: 0 <= r < |q| and: y = x*q + r // r = x.Mod(y) with: 0 <= r < |q| and: x = y*q + r
// //
// (Raymond T. Boute, ``The Euclidian definition of the functions // (Raymond T. Boute, ``The Euclidian definition of the functions
// div and mod''. ACM Transactions on Programming Languages and // div and mod''. ACM Transactions on Programming Languages and
......
...@@ -18,7 +18,7 @@ import ( ...@@ -18,7 +18,7 @@ import (
// WARNING: use of this function to encrypt plaintexts other than session keys // WARNING: use of this function to encrypt plaintexts other than session keys
// is dangerous. Use RSA OAEP in new protocols. // is dangerous. Use RSA OAEP in new protocols.
func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err os.Error) { func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err os.Error) {
k := (pub.N.Len() + 7) / 8 k := (pub.N.BitLen() + 7) / 8
if len(msg) > k-11 { if len(msg) > k-11 {
err = MessageTooLongError{} err = MessageTooLongError{}
return return
...@@ -66,7 +66,7 @@ func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out [ ...@@ -66,7 +66,7 @@ func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out [
// Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology // Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology
// (Crypto '98), // (Crypto '98),
func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err os.Error) { func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err os.Error) {
k := (priv.N.Len() + 7) / 8 k := (priv.N.BitLen() + 7) / 8
if k-(len(key)+3+8) < 0 { if k-(len(key)+3+8) < 0 {
err = DecryptionError{} err = DecryptionError{}
return return
...@@ -83,7 +83,7 @@ func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []by ...@@ -83,7 +83,7 @@ func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []by
} }
func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, msg []byte, err os.Error) { func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, msg []byte, err os.Error) {
k := (priv.N.Len() + 7) / 8 k := (priv.N.BitLen() + 7) / 8
if k < 11 { if k < 11 {
err = DecryptionError{} err = DecryptionError{}
return return
...@@ -179,7 +179,7 @@ func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash PKCS1v15Hash, hashed [] ...@@ -179,7 +179,7 @@ func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash PKCS1v15Hash, hashed []
} }
tLen := len(prefix) + hashLen tLen := len(prefix) + hashLen
k := (priv.N.Len() + 7) / 8 k := (priv.N.BitLen() + 7) / 8
if k < tLen+11 { if k < tLen+11 {
return nil, MessageTooLongError{} return nil, MessageTooLongError{}
} }
...@@ -212,7 +212,7 @@ func VerifyPKCS1v15(pub *PublicKey, hash PKCS1v15Hash, hashed []byte, sig []byte ...@@ -212,7 +212,7 @@ func VerifyPKCS1v15(pub *PublicKey, hash PKCS1v15Hash, hashed []byte, sig []byte
} }
tLen := len(prefix) + hashLen tLen := len(prefix) + hashLen
k := (pub.N.Len() + 7) / 8 k := (pub.N.BitLen() + 7) / 8
if k < tLen+11 { if k < tLen+11 {
err = VerificationError{} err = VerificationError{}
return return
......
...@@ -67,7 +67,7 @@ func TestEncryptPKCS1v15(t *testing.T) { ...@@ -67,7 +67,7 @@ func TestEncryptPKCS1v15(t *testing.T) {
if err != nil { if err != nil {
t.Errorf("Failed to open /dev/urandom") t.Errorf("Failed to open /dev/urandom")
} }
k := (rsaPrivateKey.N.Len() + 7) / 8 k := (rsaPrivateKey.N.BitLen() + 7) / 8
tryEncryptDecrypt := func(in []byte, blind bool) bool { tryEncryptDecrypt := func(in []byte, blind bool) bool {
if len(in) > k-11 { if len(in) > k-11 {
......
...@@ -50,11 +50,11 @@ func randomPrime(rand io.Reader, bits int) (p *big.Int, err os.Error) { ...@@ -50,11 +50,11 @@ func randomPrime(rand io.Reader, bits int) (p *big.Int, err os.Error) {
// randomNumber returns a uniform random value in [0, max). // randomNumber returns a uniform random value in [0, max).
func randomNumber(rand io.Reader, max *big.Int) (n *big.Int, err os.Error) { func randomNumber(rand io.Reader, max *big.Int) (n *big.Int, err os.Error) {
k := (max.Len() + 7) / 8 k := (max.BitLen() + 7) / 8
// r is the number of bits in the used in the most significant byte of // r is the number of bits in the used in the most significant byte of
// max. // max.
r := uint(max.Len() % 8) r := uint(max.BitLen() % 8)
if r == 0 { if r == 0 {
r = 8 r = 8
} }
...@@ -244,7 +244,7 @@ func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int { ...@@ -244,7 +244,7 @@ func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int {
// twice the hash length plus 2. // twice the hash length plus 2.
func EncryptOAEP(hash hash.Hash, rand io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err os.Error) { func EncryptOAEP(hash hash.Hash, rand io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err os.Error) {
hash.Reset() hash.Reset()
k := (pub.N.Len() + 7) / 8 k := (pub.N.BitLen() + 7) / 8
if len(msg) > k-2*hash.Size()-2 { if len(msg) > k-2*hash.Size()-2 {
err = MessageTooLongError{} err = MessageTooLongError{}
return return
...@@ -365,7 +365,7 @@ func decrypt(rand io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.E ...@@ -365,7 +365,7 @@ func decrypt(rand io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err os.E
// DecryptOAEP decrypts ciphertext using RSA-OAEP. // DecryptOAEP decrypts ciphertext using RSA-OAEP.
// If rand != nil, DecryptOAEP uses RSA blinding to avoid timing side-channel attacks. // If rand != nil, DecryptOAEP uses RSA blinding to avoid timing side-channel attacks.
func DecryptOAEP(hash hash.Hash, rand io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err os.Error) { func DecryptOAEP(hash hash.Hash, rand io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err os.Error) {
k := (priv.N.Len() + 7) / 8 k := (priv.N.BitLen() + 7) / 8
if len(ciphertext) > k || if len(ciphertext) > k ||
k < hash.Size()*2+2 { k < hash.Size()*2+2 {
err = DecryptionError{} err = DecryptionError{}
......
...@@ -81,8 +81,8 @@ func extract_digit() int64 { ...@@ -81,8 +81,8 @@ func extract_digit() int64 {
func next_term(k int64) { func next_term(k int64) {
// TODO(eds) If big.Int ever gets a Scale method, y2 and bigk could be int64 // TODO(eds) If big.Int ever gets a Scale method, y2 and bigk could be int64
y2.New(k*2 + 1) y2.SetInt64(k*2 + 1)
bigk.New(k) bigk.SetInt64(k)
tmp1.Lsh(numer, 1) tmp1.Lsh(numer, 1)
accum.Add(accum, tmp1) accum.Add(accum, tmp1)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment