From 0467c64d21614e4a39adad06a87c193cfb658c4e Mon Sep 17 00:00:00 2001 From: Dan Ballard Date: Thu, 16 Jan 2014 07:53:44 -0500 Subject: [PATCH] speed up for go --- primes.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/primes.go b/primes.go index cc56849..e250fce 100644 --- a/primes.go +++ b/primes.go @@ -9,11 +9,16 @@ import( "math" ) +// 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 func main() { if len(os.Args) < 2 { fmt.Println("Usage: go run primes.go [MAX]") return } + primes := make([]int, 0) max,_ := strconv.Atoi(os.Args[1]) for i:= 3; i < max; i+=2 { is_prime := true @@ -24,7 +29,8 @@ func main() { } } if is_prime { - fmt.Println(i) + primes = append(primes, i) } } + fmt.Println(primes) }