Generating prime numbers in Go

Here's a golang sieve of Eratosthenes

package main
import "fmt"

// return list of primes less than N
func sieveOfEratosthenes(N int) (primes []int) {
    b := make([]bool, N)
    for i := 2; i < N; i++ {
        if b[i] == true { continue }
        primes = append(primes, i)
        for k := i * i; k < N; k += i {
            b[k] = true
        }
    }
    return
}

func main() {
    primes := sieveOfEratosthenes(100)
    for _, p := range primes {
        fmt.Println(p)
    }
}

The simplest method to get "numbers that are divisible only with themselves and by 1", which are also known as prime numbers is: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

It's not a "simple if statement".


It seems you are looking for prime numbers. However the conditions you described are not sufficient. In fact you have to use an algorithm to generate them (up to a certain limit most probably).

This is an implementation of the Sieve of Atkin which is an optimized variation of the ancient Sieve of Eratosthenes.

Demo: http://play.golang.org/p/XXiTIpRBAu

For the sake of completeness:

package main

import (
    "fmt"
    "math"
)

// Only primes less than or equal to N will be generated
const N = 100

func main() {
    var x, y, n int
    nsqrt := math.Sqrt(N)

    is_prime := [N]bool{}

    for x = 1; float64(x) <= nsqrt; x++ {
        for y = 1; float64(y) <= nsqrt; y++ {
            n = 4*(x*x) + y*y
            if n <= N && (n%12 == 1 || n%12 == 5) {
                is_prime[n] = !is_prime[n]
            }
            n = 3*(x*x) + y*y
            if n <= N && n%12 == 7 {
                is_prime[n] = !is_prime[n]
            }
            n = 3*(x*x) - y*y
            if x > y && n <= N && n%12 == 11 {
                is_prime[n] = !is_prime[n]
            }
        }
    }

    for n = 5; float64(n) <= nsqrt; n++ {
        if is_prime[n] {
            for y = n * n; y < N; y += n * n {
                is_prime[y] = false
            }
        }
    }

    is_prime[2] = true
    is_prime[3] = true

    primes := make([]int, 0, 1270606)
    for x = 0; x < len(is_prime)-1; x++ {
        if is_prime[x] {
            primes = append(primes, x)
        }
    }

    // primes is now a slice that contains all primes numbers up to N
    // so let's print them
    for _, x := range primes {
        fmt.Println(x)
    }
}

If you don't mind a very small chance (9.1e-13 in this case) of them not being primes you can use ProbablyPrime from math/big like this (play)

import (
    "fmt"
    "math/big"
)

func main() {
    for i := 2; i < 1000; i++ {
        if big.NewInt(int64(i)).ProbablyPrime(20) {
            fmt.Printf("%d is probably prime\n", i)
        } else {
            fmt.Printf("%d is definitely not prime\n", i)
        }
    }
}

Just change the constant 20 to be as sure as you like that they are primes.

Tags:

Primes

Go