Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/math/big/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,17 @@ func (z *Int) Add(x, y *Int) *Int {
return z
}

// Inc sets z to the sum z+1 and returns z.
func (z *Int) Inc() *Int {
if z.neg {
z.abs = z.abs.sub(z.abs, intOne.abs)
z.neg = len(z.abs) > 0
} else {
z.abs = z.abs.add(z.abs, intOne.abs)
}
return z
}

// Sub sets z to the difference x-y and returns z.
func (z *Int) Sub(x, y *Int) *Int {
neg := x.neg
Expand All @@ -154,6 +165,19 @@ func (z *Int) Sub(x, y *Int) *Int {
return z
}

// Dec sets z to the difference z-1 and returns z.
func (z *Int) Dec() *Int {
if z.neg {
z.abs = z.abs.add(z.abs, intOne.abs)
} else if len(z.abs) > 0 {
z.abs = z.abs.sub(z.abs, intOne.abs)
} else {
z.abs = z.abs.add(z.abs, intOne.abs)
z.neg = true
}
return z
}

// Mul sets z to the product x*y and returns z.
func (z *Int) Mul(x, y *Int) *Int {
// x * y == x * y
Expand Down
50 changes: 50 additions & 0 deletions src/math/big/int_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1766,6 +1766,56 @@ func TestIssue22830(t *testing.T) {
}
}

func TestInc(t *testing.T) {
var i int64
for i = -1; i <= 1; i++ {
inc := NewInt(i).Inc()
add := new(Int).Add(NewInt(i), intOne)
if inc.Cmp(add) != 0 {
t.Fatalf("%v != %v", inc, add)
}
}
}

func TestDec(t *testing.T) {
var i int64
for i = -1; i <= 1; i++ {
dec := NewInt(i).Dec()
sub := new(Int).Sub(NewInt(i), intOne)
if dec.Cmp(sub) != 0 {
t.Fatalf("(%v != %v", dec, sub)
}
}
}

func BenchmarkInc(b *testing.B) {
z := new(Int)
for i := 0; i < b.N; i++ {
z.Inc()
}
}

func BenchmarkIncByAdd(b *testing.B) {
z := new(Int)
for i := 0; i < b.N; i++ {
z.Add(z, intOne)
}
}

func BenchmarkDec(b *testing.B) {
z := new(Int)
for i := 0; i < b.N; i++ {
z.Dec()
}
}

func BenchmarkDecBySub(b *testing.B) {
z := new(Int)
for i := 0; i < b.N; i++ {
z.Sub(z, intOne)
}
}

func BenchmarkSqrt(b *testing.B) {
n, _ := new(Int).SetString("1"+strings.Repeat("0", 1001), 10)
b.ResetTimer()
Expand Down