Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use golang's ProbablyPrime?

Tags:

go

primes

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?

like image 762
Shaun Avatar asked Dec 25 '22 14:12

Shaun


1 Answers

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)
}
like image 198
krait Avatar answered Jan 13 '23 06:01

krait