Created
February 21, 2019 14:29
-
-
Save a7madM/f0b845a4c27ddaa40b162153366f959b to your computer and use it in GitHub Desktop.
Primes in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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