Skip to content

Commit e21154f

Browse files
ALTreegriesemer
authored andcommitted
math/big: fix Exp when exponent is 1
Fixed bug that caused Exp(x, y, m) ( i.e. x**y (mod m) ) to return x instead of x (mod m) when y == 1. See issue page on github for more details. Added test case Fixes #9826 Change-Id: Ibabb58275a20c4231c9474199b7f1c10e54241ce Reviewed-on: https://go-review.googlesource.com/8409 Reviewed-by: Robert Griesemer <[email protected]>
1 parent 0c8fe34 commit e21154f

File tree

2 files changed

+8
-0
lines changed

2 files changed

+8
-0
lines changed

src/math/big/int_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,7 @@ var expTests = []struct {
525525
{"1234", "-1", "1", "0"},
526526

527527
// misc
528+
{"5", "1", "3", "2"},
528529
{"5", "-7", "", "1"},
529530
{"-5", "-7", "", "1"},
530531
{"5", "0", "", "1"},

src/math/big/nat.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,13 @@ func (z nat) expNN(x, y, m nat) nat {
888888
}
889889
// y > 0
890890

891+
// x**1 mod m == x mod m
892+
if len(y) == 1 && y[0] == 1 && len(m) != 0 {
893+
_, z = z.div(z, x, m)
894+
return z
895+
}
896+
// y > 1
897+
891898
if len(m) != 0 {
892899
// We likely end up being as long as the modulus.
893900
z = z.make(len(m))

0 commit comments

Comments
 (0)