Problem 10 — Summation of primes
“The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.”
For this one, we will need to re-use our isPrime() function. Basically, we need to go from 2 to the 2000000 and check every number. If it is prime, then add it up to a variable.
142913828922
package main
import (
"fmt"
"math"
)
const (
ICount = 2000000
)
func main() {
var res = 0
for i := 2; i <= ICount; i++ {
if isPrime(i) {
fmt.Println(i)
res += i
}
}
fmt.Println("--- res = ", res)
}
func isPrime(value int) bool {
for i := 2; i <= int(math.Floor(float64(value)/2)); i++ {
if value%i == 0 {
return false
}
}
return value > 1
}