1
0
mirror of https://github.com/golang/go synced 2024-11-24 17:00:01 -07:00

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
This commit is contained in:
Robert Griesemer 2010-05-03 18:48:05 -07:00
parent 32df678894
commit b9caa4ac56
8 changed files with 332 additions and 172 deletions

View File

@ -14,8 +14,11 @@ type Int struct {
}
// New allocates and returns a new Int set to x.
func (z *Int) New(x int64) *Int {
var intOne = &Int{false, natOne}
// SetInt64 sets z to x and returns z.
func (z *Int) SetInt64(x int64) *Int {
z.neg = false
if x < 0 {
z.neg = true
@ -27,7 +30,9 @@ func (z *Int) New(x int64) *Int {
// 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.
@ -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 {
neg := x.neg
if x.neg == y.neg {
// x + y == x + y
// (-x) + (-y) == -(x + y)
z.neg = x.neg
z.abs = z.abs.add(x.abs, y.abs)
} else {
// x + (-y) == x - y == -(y - x)
// (-x) + y == y - x == -(x - y)
if x.abs.cmp(y.abs) >= 0 {
z.neg = x.neg
z.abs = z.abs.sub(x.abs, y.abs)
} else {
z.neg = !x.neg
neg = !neg
z.abs = z.abs.sub(y.abs, x.abs)
}
}
if len(z.abs) == 0 {
z.neg = false // 0 has no sign
}
z.neg = len(z.abs) > 0 && neg // 0 has no sign
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 {
neg := x.neg
if x.neg != y.neg {
// x - (-y) == x + y
// (-x) - y == -(x + y)
z.neg = x.neg
z.abs = z.abs.add(x.abs, y.abs)
} else {
// x - y == x - y == -(y - x)
// (-x) - (-y) == y - x == -(x - y)
if x.abs.cmp(y.abs) >= 0 {
z.neg = x.neg
z.abs = z.abs.sub(x.abs, y.abs)
} else {
z.neg = !x.neg
neg = !neg
z.abs = z.abs.sub(y.abs, x.abs)
}
}
if len(z.abs) == 0 {
z.neg = false // 0 has no sign
}
z.neg = len(z.abs) > 0 && neg // 0 has no sign
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 {
// x * y == x * y
// x * (-y) == -(x * y)
@ -100,38 +99,117 @@ func (z *Int) Mul(x, y *Int) *Int {
}
// Div calculates q = (x-r)/y and sets z = q.
func (z *Int) Div(x, y *Int) *Int {
r := new(Int)
div(z, r, x, y)
// Quo sets z to the quotient x/y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// See QuoRem for more details.
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
}
// Mod calculates q = (x-r)/y and sets z = r.
func (z *Int) Mod(x, y *Int) *Int {
q := new(Int)
div(q, z, x, y)
// Rem sets z to the remainder x%y for y != 0 and returns z.
// If y == 0, a division-by-zero run-time panic occurs.
// See QuoRem for more details.
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
}
// DivMod calculates q = (x-r)/y and sets z = q. (It returns z, r.)
func (z *Int) DivMod(x, y, r *Int) (*Int, *Int) {
div(z, r, x, y)
// QuoRem sets z to the quotient x/y and r to the remainder x%y
// and returns the pair (z, r) for y != 0.
// 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
}
func div(q, r, x, y *Int) {
q.neg = x.neg != y.neg
r.neg = x.neg
q.abs, r.abs = q.abs.div(r.abs, x.abs, y.abs)
return
// Div sets z to the quotient 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) Div(x, y *Int) *Int {
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
}
// Neg computes z = -x.
// 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 the negation z = -x.
func (z *Int) Neg(x *Int) *Int {
z.abs = z.abs.set(x.abs)
z.neg = len(z.abs) > 0 && !x.neg // 0 has no sign
@ -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
// 0 if x == y
@ -205,26 +283,23 @@ func (z *Int) SetString(s string, base int) (*Int, bool) {
goto Error
}
neg := false
if s[0] == '-' {
z.neg = true
neg = true
s = s[1:]
} else {
z.neg = false
}
z.abs, _, scanned = z.abs.scan(s, base)
if scanned != len(s) {
goto Error
}
if len(z.abs) == 0 {
z.neg = false // 0 has no sign
}
z.neg = len(z.abs) > 0 && neg // 0 has no sign
return z, true
Error:
z.neg = false
z.abs = nil
z.neg = false
return z, false
}
@ -234,7 +309,6 @@ Error:
func (z *Int) SetBytes(b []byte) *Int {
s := int(_S)
z.abs = z.abs.make((len(b) + s - 1) / s)
z.neg = false
j := 0
for len(b) >= s {
@ -262,7 +336,7 @@ func (z *Int) SetBytes(b []byte) *Int {
}
z.abs = z.abs.norm()
z.neg = false
return z
}
@ -289,14 +363,10 @@ func (z *Int) Bytes() []byte {
}
// Len returns the length of the absolute value of z in bits. Zero is
// considered to have a length of zero.
func (z *Int) Len() int {
if len(z.abs) == 0 {
return 0
}
return len(z.abs)*_W - int(leadingZeros(z.abs[len(z.abs)-1]))
// BitLen returns the length of the absolute value of z in bits.
// The bit length of 0 is 0.
func (z *Int) BitLen() int {
return z.abs.bitLen()
}
@ -304,7 +374,7 @@ func (z *Int) Len() int {
// See Knuth, volume 2, section 4.6.3.
func (z *Int) Exp(x, y, m *Int) *Int {
if y.neg || len(y.abs) == 0 {
z.New(1)
z.SetInt64(1)
z.neg = x.neg
return z
}
@ -315,7 +385,7 @@ func (z *Int) Exp(x, y, m *Int) *Int {
}
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
}
@ -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.
func GcdInt(d, x, y, a, b *Int) {
if a.neg || b.neg {
d.New(0)
d.SetInt64(0)
if x != nil {
x.New(0)
x.SetInt64(0)
}
if y != nil {
y.New(0)
y.SetInt64(0)
}
return
}
@ -340,9 +410,9 @@ func GcdInt(d, x, y, a, b *Int) {
B := new(Int).Set(b)
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)
q := new(Int)
@ -350,7 +420,7 @@ func GcdInt(d, x, y, a, b *Int) {
for len(B.abs) > 0 {
r := new(Int)
q, r = q.DivMod(A, B, r)
q, r = q.QuoRem(A, B, r)
A, B = B, r
@ -382,13 +452,15 @@ func GcdInt(d, x, y, a, b *Int) {
// 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 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.
func (z *Int) Lsh(x *Int, n uint) *Int {
z.neg = x.neg
z.abs = z.abs.shl(x.abs, n)
z.neg = x.neg
return z
}
@ -397,18 +469,19 @@ func (z *Int) Lsh(x *Int, n uint) *Int {
func (z *Int) Rsh(x *Int, n uint) *Int {
if x.neg {
// (-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 = t.shr(t, n)
z.abs = t.add(t, natOne)
z.neg = true // z cannot be zero if x is negative
return z
}
z.neg = false
z.abs = z.abs.shr(x.abs, n)
z.neg = false
return z
}
// And sets z = x & y and returns z.
func (z *Int) And(x, y *Int) *Int {
if x.neg == y.neg {
@ -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)
x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne)
z.neg = true
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
}
// x & y == x & y
z.neg = false
z.abs = z.abs.and(x.abs, y.abs)
z.neg = false
return z
}
@ -434,8 +507,8 @@ func (z *Int) And(x, y *Int) *Int {
// x & (-y) == x & ^(y-1) == x &^ (y-1)
y1 := z.abs.sub(y.abs, natOne)
z.neg = false
z.abs = z.abs.andNot(x.abs, y1)
z.neg = false
return z
}
@ -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)
x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne)
z.neg = false
z.abs = z.abs.andNot(y1, x1)
z.neg = false
return z
}
// x &^ y == x &^ y
z.neg = false
z.abs = z.abs.andNot(x.abs, y.abs)
z.neg = false
return z
}
if x.neg {
// (-x) &^ y == ^(x-1) &^ y == ^(x-1) & ^y == ^((x-1) | y) == -(((x-1) | y) + 1)
x1 := z.abs.sub(x.abs, natOne)
z.neg = true
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
}
// x &^ (-y) == x &^ ^(y-1) == x & (y-1)
y1 := z.abs.add(y.abs, natOne)
z.neg = false
z.abs = z.abs.and(x.abs, y1)
z.neg = false
return z
}
@ -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)
x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne)
z.neg = true
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
}
// x | y == x | y
z.neg = false
z.abs = z.abs.or(x.abs, y.abs)
z.neg = false
return z
}
@ -499,8 +572,8 @@ func (z *Int) Or(x, y *Int) *Int {
// x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1)
y1 := z.abs.sub(y.abs, natOne)
z.neg = true
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
}
@ -512,26 +585,26 @@ func (z *Int) Xor(x, y *Int) *Int {
// (-x) ^ (-y) == ^(x-1) ^ ^(y-1) == (x-1) ^ (y-1)
x1 := nat{}.sub(x.abs, natOne)
y1 := z.abs.sub(y.abs, natOne)
z.neg = false
z.abs = z.abs.xor(x1, y1)
z.neg = false
return z
}
// x ^ y == x ^ y
z.neg = false
z.abs = z.abs.xor(x.abs, y.abs)
z.neg = false
return z
}
// x.neg != y.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)
y1 := z.abs.sub(y.abs, natOne)
z.neg = true
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
}
@ -540,13 +613,13 @@ func (z *Int) Xor(x, y *Int) *Int {
func (z *Int) Not(x *Int) *Int {
if x.neg {
// ^(-x) == ^(^(x-1)) == x-1
z.neg = false
z.abs = z.abs.sub(x.abs, natOne)
z.neg = false
return z
}
// ^x == -x-1 == -(x+1)
z.neg = true
z.abs = z.abs.add(x.abs, natOne)
z.neg = true // z cannot be zero if x is positive
return z
}

View File

@ -11,9 +11,13 @@ import (
"testing/quick"
)
func newZ(x int64) *Int {
var z Int
return z.New(x)
func isNormalized(x *Int) bool {
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 {
var sumZZ = []argZZ{
argZZ{newZ(0), newZ(0), newZ(0)},
argZZ{newZ(1), newZ(1), newZ(0)},
argZZ{newZ(1111111110), newZ(123456789), newZ(987654321)},
argZZ{newZ(-1), newZ(-1), newZ(0)},
argZZ{newZ(864197532), newZ(-123456789), newZ(987654321)},
argZZ{newZ(-1111111110), newZ(-123456789), newZ(-987654321)},
argZZ{NewInt(0), NewInt(0), NewInt(0)},
argZZ{NewInt(1), NewInt(1), NewInt(0)},
argZZ{NewInt(1111111110), NewInt(123456789), NewInt(987654321)},
argZZ{NewInt(-1), NewInt(-1), NewInt(0)},
argZZ{NewInt(864197532), NewInt(-123456789), NewInt(987654321)},
argZZ{NewInt(-1111111110), NewInt(-123456789), NewInt(-987654321)},
}
var prodZZ = []argZZ{
argZZ{newZ(0), newZ(0), newZ(0)},
argZZ{newZ(0), newZ(1), newZ(0)},
argZZ{newZ(1), newZ(1), newZ(1)},
argZZ{newZ(-991 * 991), newZ(991), newZ(-991)},
argZZ{NewInt(0), NewInt(0), NewInt(0)},
argZZ{NewInt(0), NewInt(1), NewInt(0)},
argZZ{NewInt(1), NewInt(1), NewInt(1)},
argZZ{NewInt(-991 * 991), NewInt(991), NewInt(-991)},
// TODO(gri) add larger products
}
@ -46,6 +50,9 @@ func TestSetZ(t *testing.T) {
for _, a := range sumZZ {
var z Int
z.Set(a.z)
if !isNormalized(&z) {
t.Errorf("%v is not normalized", z)
}
if (&z).Cmp(a.z) != 0 {
t.Errorf("got z = %v; want %v", z, a.z)
}
@ -56,6 +63,9 @@ func TestSetZ(t *testing.T) {
func testFunZZ(t *testing.T, msg string, f funZZ, a argZZ) {
var z Int
f(&z, a.x, a.y)
if !isNormalized(&z) {
t.Errorf("msg: %v is not normalized", z, msg)
}
if (&z).Cmp(a.z) != 0 {
t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z)
}
@ -186,7 +196,7 @@ func TestSetString(t *testing.T) {
for i, test := range fromStringTests {
n1, ok1 := new(Int).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 {
t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok)
continue
@ -195,6 +205,13 @@ func TestSetString(t *testing.T) {
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 {
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) {
}
type divSignsTest struct {
type divisionSignsTest struct {
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"
var divSignsTests = []divSignsTest{
divSignsTest{5, 3, 1, 2},
divSignsTest{-5, 3, -1, -2},
divSignsTest{5, -3, -1, 2},
divSignsTest{-5, -3, 1, -2},
divSignsTest{1, 2, 0, 1},
// Examples from the Go Language Spec, section "Arithmetic operators"
var divisionSignsTests = []divisionSignsTest{
divisionSignsTest{5, 3, 1, 2, 1, 2},
divisionSignsTest{-5, 3, -1, -2, -2, 1},
divisionSignsTest{5, -3, -1, 2, -1, 2},
divisionSignsTest{-5, -3, 1, -2, 2, 1},
divisionSignsTest{1, 2, 0, 1, 0, 1},
divisionSignsTest{8, 4, 2, 0, 2, 0},
}
func TestDivSigns(t *testing.T) {
for i, test := range divSignsTests {
x := new(Int).New(test.x)
y := new(Int).New(test.y)
r := new(Int)
q, r := new(Int).DivMod(x, y, r)
expectedQ := new(Int).New(test.q)
expectedR := new(Int).New(test.r)
func TestDivisionSigns(t *testing.T) {
for i, test := range divisionSignsTests {
x := NewInt(test.x)
y := NewInt(test.y)
q := NewInt(test.q)
r := NewInt(test.r)
d := NewInt(test.d)
m := NewInt(test.m)
if q.Cmp(expectedQ) != 0 || r.Cmp(expectedR) != 0 {
t.Errorf("#%d: got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR)
q1 := new(Int).Quo(x, y)
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) {
}
func checkDiv(x, y []byte) bool {
func checkQuo(x, y []byte) bool {
u := new(Int).SetBytes(x)
v := new(Int).SetBytes(y)
@ -282,7 +343,7 @@ func checkDiv(x, y []byte) bool {
}
r := new(Int)
q, r := new(Int).DivMod(u, v, r)
q, r := new(Int).QuoRem(u, v, r)
if r.Cmp(v) >= 0 {
return false
@ -296,20 +357,20 @@ func checkDiv(x, y []byte) bool {
}
type divTest struct {
type quoTest struct {
x, y string
q, r string
}
var divTests = []divTest{
divTest{
var quoTests = []quoTest{
quoTest{
"476217953993950760840509444250624797097991362735329973741718102894495832294430498335824897858659711275234906400899559094370964723884706254265559534144986498357",
"9353930466774385905609975137998169297361893554149986716853295022578535724979483772383667534691121982974895531435241089241440253066816724367338287092081996",
"50911",
"1",
},
divTest{
quoTest{
"11510768301994997771168",
"1328165573307167369775",
"8",
@ -318,19 +379,19 @@ var divTests = []divTest{
}
func TestDiv(t *testing.T) {
if err := quick.Check(checkDiv, nil); err != nil {
func TestQuo(t *testing.T) {
if err := quick.Check(checkQuo, nil); err != nil {
t.Error(err)
}
for i, test := range divTests {
for i, test := range quoTests {
x, _ := new(Int).SetString(test.x, 10)
y, _ := new(Int).SetString(test.y, 10)
expectedQ, _ := new(Int).SetString(test.q, 10)
expectedR, _ := new(Int).SetString(test.r, 10)
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 {
t.Errorf("#%d got (%s, %s) want (%s, %s)", i, q, r, expectedQ, expectedR)
@ -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
// a code path which only triggers 1 in 10^{-19} cases.
@ -347,7 +408,7 @@ func TestDivStepD6(t *testing.T) {
v := &Int{false, nat{5, 2 + 1<<(_W-1), 1 << (_W - 1)}}
r := new(Int)
q, r := new(Int).DivMod(u, v, r)
q, r := new(Int).QuoRem(u, v, r)
const expectedQ64 = "18446744073709551613"
const expectedR64 = "3138550867693340382088035895064302439801311770021610913807"
const expectedQ32 = "4294967293"
@ -359,35 +420,38 @@ func TestDivStepD6(t *testing.T) {
}
type lenTest struct {
type bitLenTest struct {
in string
out int
}
var lenTests = []lenTest{
lenTest{"0", 0},
lenTest{"1", 1},
lenTest{"2", 2},
lenTest{"4", 3},
lenTest{"0x8000", 16},
lenTest{"0x80000000", 32},
lenTest{"0x800000000000", 48},
lenTest{"0x8000000000000000", 64},
lenTest{"0x80000000000000000000", 80},
var bitLenTests = []bitLenTest{
bitLenTest{"-1", 1},
bitLenTest{"0", 0},
bitLenTest{"1", 1},
bitLenTest{"2", 2},
bitLenTest{"4", 3},
bitLenTest{"0xabc", 12},
bitLenTest{"0x8000", 16},
bitLenTest{"0x80000000", 32},
bitLenTest{"0x800000000000", 48},
bitLenTest{"0x8000000000000000", 64},
bitLenTest{"0x80000000000000000000", 80},
bitLenTest{"-0x4000000000000000000000", 87},
}
func TestLen(t *testing.T) {
for i, test := range lenTests {
n, ok := new(Int).SetString(test.in, 0)
func TestBitLen(t *testing.T) {
for i, test := range bitLenTests {
x, ok := new(Int).SetString(test.in, 0)
if !ok {
t.Errorf("#%d test input invalid: %s", i, test.in)
continue
}
if n.Len() != test.out {
t.Errorf("#%d got %d want %d\n", i, n.Len(), test.out)
if n := x.BitLen(); n != test.out {
t.Errorf("#%d got %d want %d\n", i, n, test.out)
}
}
}
@ -404,6 +468,7 @@ var expTests = []expTest{
expTest{"-5", "0", "", "-1"},
expTest{"5", "1", "", "5"},
expTest{"-5", "1", "", "-5"},
expTest{"-2", "3", "2", "0"},
expTest{"5", "2", "", "25"},
expTest{"1", "65537", "2", "1"},
expTest{"0x8000000000000000", "2", "", "0x40000000000000000000000000000000"},
@ -436,13 +501,16 @@ func TestExp(t *testing.T) {
}
if !ok1 || !ok2 || !ok3 || !ok4 {
t.Errorf("#%d error in input", i)
t.Errorf("#%d: error in input", i)
continue
}
z := new(Int).Exp(x, y, m)
if !isNormalized(z) {
t.Errorf("#%d: %v is not normalized", i, *z)
}
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{
func TestGcd(t *testing.T) {
for i, test := range gcdTests {
a := new(Int).New(test.a)
b := new(Int).New(test.b)
a := NewInt(test.a)
b := NewInt(test.b)
x := new(Int)
y := new(Int)
d := new(Int)
expectedX := new(Int).New(test.x)
expectedY := new(Int).New(test.y)
expectedD := new(Int).New(test.d)
expectedX := NewInt(test.x)
expectedY := NewInt(test.y)
expectedD := NewInt(test.d)
GcdInt(d, x, y, a, b)
@ -594,8 +662,11 @@ func TestRsh(t *testing.T) {
expected, _ := new(Int).SetString(test.out, 10)
out := new(Int).Rsh(in, test.shift)
if !isNormalized(out) {
t.Errorf("#%d: %v is not normalized", i, *out)
}
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) {
expected, _ := new(Int).SetString(test.out, 10)
z.Rsh(z, test.shift)
if !isNormalized(z) {
t.Errorf("#%d: %v is not normalized", i, *z)
}
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) {
expected, _ := new(Int).SetString(test.out, 10)
out := new(Int).Lsh(in, test.shift)
if !isNormalized(out) {
t.Errorf("#%d: %v is not normalized", i, *out)
}
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) {
expected, _ := new(Int).SetString(test.out, 10)
z.Lsh(z, test.shift)
if !isNormalized(z) {
t.Errorf("#%d: %v is not normalized", i, *z)
}
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) {
out := new(Int).Lsh(in, 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 {
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 {
@ -678,8 +761,11 @@ func TestLshRsh(t *testing.T) {
out := new(Int).Lsh(in, test.shift)
out.Rsh(out, test.shift)
if !isNormalized(out) {
t.Errorf("#%d: %v is not normalized", i, *out)
}
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{
bitwiseTest{"0x00", "0x01", "0x00", "0x01", "0x01", "0x00"},
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{"0x01", "0x01", "0x01", "0x01", "0x00", "0x00"},
bitwiseTest{"-0x01", "-0x01", "-0x01", "-0x01", "0x00", "0x00"},

View File

@ -356,7 +356,7 @@ func karatsuba(z, x, y nat) {
// alias returns true if x and y share the same base array.
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 {
// m >= n > 1
// 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
}
@ -757,7 +757,7 @@ func (z nat) shl(x nat, s uint) nat {
// determine if z can be reused
// 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
}
@ -780,7 +780,7 @@ func (z nat) shr(x nat, s uint) nat {
// determine if z can be reused
// 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
}

View File

@ -253,7 +253,7 @@ func (x *Integer) QuoRem(y *Integer) (*Integer, *Integer) {
// Div and Mod implement Euclidian division and modulus:
//
// 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
// div and mod''. ACM Transactions on Programming Languages and

View File

@ -18,7 +18,7 @@ import (
// WARNING: use of this function to encrypt plaintexts other than session keys
// is dangerous. Use RSA OAEP in new protocols.
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 {
err = MessageTooLongError{}
return
@ -66,7 +66,7 @@ func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out [
// Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology
// (Crypto '98),
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 {
err = DecryptionError{}
return
@ -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) {
k := (priv.N.Len() + 7) / 8
k := (priv.N.BitLen() + 7) / 8
if k < 11 {
err = DecryptionError{}
return
@ -179,7 +179,7 @@ func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash PKCS1v15Hash, hashed []
}
tLen := len(prefix) + hashLen
k := (priv.N.Len() + 7) / 8
k := (priv.N.BitLen() + 7) / 8
if k < tLen+11 {
return nil, MessageTooLongError{}
}
@ -212,7 +212,7 @@ func VerifyPKCS1v15(pub *PublicKey, hash PKCS1v15Hash, hashed []byte, sig []byte
}
tLen := len(prefix) + hashLen
k := (pub.N.Len() + 7) / 8
k := (pub.N.BitLen() + 7) / 8
if k < tLen+11 {
err = VerificationError{}
return

View File

@ -67,7 +67,7 @@ func TestEncryptPKCS1v15(t *testing.T) {
if err != nil {
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 {
if len(in) > k-11 {

View File

@ -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).
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
// max.
r := uint(max.Len() % 8)
r := uint(max.BitLen() % 8)
if r == 0 {
r = 8
}
@ -244,7 +244,7 @@ func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int {
// 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) {
hash.Reset()
k := (pub.N.Len() + 7) / 8
k := (pub.N.BitLen() + 7) / 8
if len(msg) > k-2*hash.Size()-2 {
err = MessageTooLongError{}
return
@ -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.
// 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) {
k := (priv.N.Len() + 7) / 8
k := (priv.N.BitLen() + 7) / 8
if len(ciphertext) > k ||
k < hash.Size()*2+2 {
err = DecryptionError{}

View File

@ -81,8 +81,8 @@ func extract_digit() int64 {
func next_term(k int64) {
// TODO(eds) If big.Int ever gets a Scale method, y2 and bigk could be int64
y2.New(k*2 + 1)
bigk.New(k)
y2.SetInt64(k*2 + 1)
bigk.SetInt64(k)
tmp1.Lsh(numer, 1)
accum.Add(accum, tmp1)