2014-01-15 15:53:35 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
// Go version of a prime number finder
|
|
|
|
|
|
|
|
import(
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
"math"
|
|
|
|
)
|
|
|
|
|
2014-01-16 12:53:44 +00:00
|
|
|
// In stead of in place printing of each prime, it seems
|
|
|
|
// fmt.Println is costly, and causes the program to take
|
|
|
|
// 7x more time, so we gain speed at the expense of RAM
|
|
|
|
// by storing them all in a slice and printing once
|
2014-01-15 15:53:35 +00:00
|
|
|
func main() {
|
|
|
|
if len(os.Args) < 2 {
|
|
|
|
fmt.Println("Usage: go run primes.go [MAX]")
|
|
|
|
return
|
|
|
|
}
|
2014-01-16 12:53:44 +00:00
|
|
|
primes := make([]int, 0)
|
2014-01-15 15:53:35 +00:00
|
|
|
max,_ := strconv.Atoi(os.Args[1])
|
|
|
|
for i:= 3; i < max; i+=2 {
|
|
|
|
is_prime := true
|
|
|
|
for j := 3; j <= int(math.Ceil(math.Sqrt(float64(i)))); j+=2 {
|
|
|
|
if i % j == 0 {
|
|
|
|
is_prime = false
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if is_prime {
|
2014-01-16 12:53:44 +00:00
|
|
|
primes = append(primes, i)
|
2014-01-15 15:53:35 +00:00
|
|
|
}
|
|
|
|
}
|
2014-01-16 12:53:44 +00:00
|
|
|
fmt.Println(primes)
|
2014-01-15 15:53:35 +00:00
|
|
|
}
|