GO: Check if a number is prime
Checking if a number is prime in the fastest and most efficient way is a trivial task for every programming language. Go offers math package with built in function big to perform task in a basic but still efficient fashion.
Ints
For integer types, use ProbablyPrime(0)
from package math/big
. This primality test is 100% accurate for inputs less than 264.
Code example:
const n = 1212121
if big.NewInt(n).ProbablyPrime(0) {
fmt.Println(n, "is prime")
} else {
fmt.Println(n, "is not prime")
}
Larger numbers
For larger numbers, you need to provide the desired number of tests to ProbablyPrime(n). For n tests, the probability of returning true for a randomly chosen non-prime is at most (1/4)n. A common choice is to use n = 20; this gives a false positive rate 0.000,000,000,001.
z := new(big.Int)
fmt.Sscan("20828378347937489020982309820938029380947893749", z)
if z.ProbablyPrime(20) {
fmt.Println(z, "is probably prime")
} else {
fmt.Println(z, "is not prime")
}
Disclaimer: this tutorial doesn’t take into account algorithm efficiency optimization
If you want to support my work feel free to send a tip:
$BTC: 1EtMQNXADe5ZoSgbwox7Ug5TPvP8YWSpL3
$QRL: Q010400e08175fe9823e6caa1aa3359686d7251a40eb432230d55f5b4e7388ec1c947b4361fb5cf