]> Cypherpunks repositories - gostls13.git/commitdiff
math/big: panic if n <= 0 for ProbablyPrime
authorShenghou Ma <minux@golang.org>
Mon, 5 Jan 2015 21:39:34 +0000 (16:39 -0500)
committerMinux Ma <minux@golang.org>
Mon, 5 Jan 2015 23:11:35 +0000 (23:11 +0000)
Fixes #9509

Change-Id: I3b86745d38e09093fe2f4b918d774bd6608727d7
Reviewed-on: https://go-review.googlesource.com/2313
Reviewed-by: Robert Griesemer <gri@golang.org>
src/math/big/int.go
src/math/big/int_test.go

index d22e39e7c94fa3591b61236eb433e4130bdf0d86..b6c7070d9d974fdc2fbbbd84c0f1be7fff6b981d 100644 (file)
@@ -736,8 +736,11 @@ func (z *Int) binaryGCD(a, b *Int) *Int {
 
 // ProbablyPrime performs n Miller-Rabin tests to check whether x is prime.
 // If it returns true, x is prime with probability 1 - 1/4^n.
-// If it returns false, x is not prime.
+// If it returns false, x is not prime. n must be >0.
 func (x *Int) ProbablyPrime(n int) bool {
+       if n <= 0 {
+               panic("non-positive n for ProbablyPrime")
+       }
        return !x.neg && x.abs.probablyPrime(n)
 }
 
index 6070cf325d206ed6ec508cf3805ac3dfac9c23c6..af3af910e9a366b318b3d75a7bdfa8102168f14d 100644 (file)
@@ -989,6 +989,21 @@ func TestProbablyPrime(t *testing.T) {
                        break
                }
        }
+
+       // check that ProbablyPrime panics if n <= 0
+       c := NewInt(11) // a prime
+       for _, n := range []int{-1, 0, 1} {
+               func() {
+                       defer func() {
+                               if n <= 0 && recover() == nil {
+                                       t.Fatalf("expected panic from ProbablyPrime(%d)", n)
+                               }
+                       }()
+                       if !c.ProbablyPrime(n) {
+                               t.Fatalf("%v should be a prime", c)
+                       }
+               }()
+       }
 }
 
 type intShiftTest struct {