How do you use golang's ProbablyPrime?

huangapple go评论79阅读模式
英文:

How do you use golang's ProbablyPrime?

问题

我的尝试总是返回false How do you use golang's ProbablyPrime?

package main

import (
    "fmt"
    "math/big"
)

func main() {
    i := new(big.Int)
    j := i.ProbablyPrime(2)
    fmt.Println(j)
}

有人可以告诉我我做错了什么吗?

英文:

My attempts always return false How do you use golang's ProbablyPrime?

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是否为质数,而不是nn是一个因子,用于指示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.

huangapple
  • 本文由 发表于 2014年1月28日 14:26:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/21398396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定