Question

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?

Was it helpful?

Solution

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)
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top