Generating prime numbers in Go

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

  EDIT   : The question essentially asks to generate prime numbers up to a certain limit. The original question follows.

I want my if statement to become true if only these two conditions are met:

for i := 2; i <= 10; i++ {

    if i%i == 0 && i%1 == 0 {

    } else {

    }
}

In this case every possible number gets past these conditions, however I want only the numbers 2, 3, 5, 7, 11... basically numbers that are divisible only with themselves and by 1 to get past, with the exception being the very first 2 . How can I do this?

Thanks

Answers

http://en.wikipedia.org/wiki/Prime_number http://en.wikipedia.org/wiki/Prime_number

http://en.wikipedia.org/wiki/Sieve_of_Atkin http://en.wikipedia.org/wiki/Sieve_of_Atkin

http://play.golang.org/p/XXiTIpRBAu 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)
    }
}

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/21854191/generating-prime-numbers-in-go

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils