英文:
How do you use golang's ProbablyPrime?
问题
我的尝试总是返回false
package main
import (
"fmt"
"math/big"
)
func main() {
i := new(big.Int)
j := i.ProbablyPrime(2)
fmt.Println(j)
}
有人可以告诉我我做错了什么吗?
英文:
My attempts always return false
package main
import (
"fmt"
"math/big"
)
func main() {
i := new(big.Int)
j := i.ProbablyPrime(2)
fmt.Println(j)
}
Can anyone let me know what I am doing wrong?
答案1
得分: 6
根据方法文档的描述:
> ProbablyPrime函数使用n个Miller-Rabin测试来检查x是否为素数。如果返回true,则x是素数的概率为1 - 1/4^n。如果返回false,则x不是素数。
你传递给该方法的参数n,并不是你要测试是否为素数的数字,而是确定素数猜测的准确性的参数:n的值越高,猜测的准确性就越高,但计算量也会增加。
如果你想测试2是否为素数,你可以这样做(http://play.golang.org/p/ZGx4XOd6WA):
package main
import (
"fmt"
"math/big"
)
func main() {
i := big.NewInt(2)
isPrime := i.ProbablyPrime(1)
fmt.Println(isPrime)
}
英文:
As described in the method documentation:
> 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.
n, the argument you pass to the method, is not the number you're trying to test for primality, but rather determines the accuracy with which the prime guess is made: the higher the value of n, the more accurate the guess will be, at the expense of additional computation.
If you want to test whether 2 is prime, you may do (http://play.golang.org/p/ZGx4XOd6WA):
package main
import (
"fmt"
"math/big"
)
func main() {
i := big.NewInt(2)
isPrime := i.ProbablyPrime(1)
fmt.Println(isPrime)
}
答案2
得分: 4
x.ProbablyPrime(n)
检查的是x
是否为质数,而不是n
。n
是一个因子,用于指示ProbablyPrime
尝试确定x
的质性的难度。n
越大,ProbablyPrime
所需的时间越长,正确的可能性也越大。具体来说,根据文档:
> 如果返回true,则x是质数的概率为1 - 1/4^n
所以你想要的是:
x := big.NewInt(2)
fmt.Println(x.ProbablyPrime(4))
在Go Playground上运行它这里。
英文:
x.ProbablyPrime(n)
checks whether x
is prime, not n
. n
is a factor which indicates how hard ProbablyPrime
will try to determine x
's primality. The higher n
is, the longer ProbablyPrime
will take, and the more likely it is to be correct. Specifically, from the documentation:
> If it returns true, x is prime with probability 1 - 1/4^n
So what you want is instead:
x := big.NewInt(2)
fmt.Println(x.ProbablyPrime(4))
Run it here on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论