package main import( "fmt" "crypto/rand" "math/big" )
funcmain() { //从128开始,这样就能够将(max.BitLen() % 8) == 0的情况包含在里面 for n := 128; n < 140; n++ { b := new(big.Int).SetInt64(int64(n)) //将new(big.Int)设为int64(n)并返回new(big.Int) fmt.Printf("max Int is : %v\n", b) i, err := rand.Int(rand.Reader, b) if err != nil { fmt.Printf("Can't generate random value: %v, %v", i, err) } fmt.Printf("rand Int is : %v\n", i) } }
bogon:~ user$ go run testGo.go max Int is : 128 rand Int is : 25 max Int is : 129 rand Int is : 117 max Int is : 130 rand Int is : 85 max Int is : 131 rand Int is : 62 max Int is : 132 rand Int is : 27 max Int is : 133 rand Int is : 120 max Int is : 134 rand Int is : 10 max Int is : 135 rand Int is : 27 max Int is : 136 rand Int is : 11 max Int is : 137 rand Int is : 119 max Int is : 138 rand Int is : 35 max Int is : 139 rand Int is : 83
funcmain() { for n := 2; n < 10; n++ { p, err := rand.Prime(rand.Reader, n) //n代表位数,比如3为2位,127为7位 if err != nil { fmt.Printf("Can't generate %d-bit prime: %v", n, err) } if p.BitLen() != n { //返回p的绝对值的字位数,0的字位数为0 fmt.Printf("%v is not %d-bit", p, n) } if !p.ProbablyPrime(32) { //对p进行32次Miller-Rabin质数检测。如果方法返回真则p是质数的几率为1-(1/4)**32;否则p不是质数 fmt.Printf("%v is not prime", p) } fmt.Println(p) } }
1 2 3 4 5 6 7 8 9
bogon:~ user$ go run testGo.go 3 7 13 31 53 109 223 439