Skip to content

Instantly share code, notes, and snippets.

@a7madM
Created February 21, 2019 14:29
Show Gist options
  • Save a7madM/f0b845a4c27ddaa40b162153366f959b to your computer and use it in GitHub Desktop.
Save a7madM/f0b845a4c27ddaa40b162153366f959b to your computer and use it in GitHub Desktop.
Primes in Golang
package main
import (
"fmt"
"math"
)
func main() {
sum := summation(2000000)
fmt.Println(sum)
}
func primes(limit int) []int {
primes := []int{}
for i := 0; i <= limit; i++ {
if isPrime(i) {
primes = append(primes, i)
}
}
return primes
}
func summation(limit int) int {
primes := primes(limit)
sum := 0
for i := 0; i < len(primes); i++ {
sum += primes[i]
}
return sum
}
func isPrime(n int) bool {
if n < 2 {
return false
}
max := int(math.Sqrt(float64(n)))
for i := 2; i <= max; i++ {
if n%i == 0 {
return false
}
}
return true
}
package main
import (
"fmt"
"testing"
)
func BenchmarkSummation(b *testing.B) {
fmt.Println("Benchmark Limit 2000000")
summation(2000000)
}
# in terminal run $ go test -bench=.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment