2 of 7 added 5 characters in body

I am trying to find all primes less than 2,000,000 and sum them together. My code currently takes 1'36" to run. Is there a faster way to get my solution?


Yes. For example,

142913828922
3.860761ms

versus your

142913828922
1m35.090248409s

prime.go:

package main

import (
    "fmt"
    "time"
)

const (
    prime    = 0x00
    notprime = 0x80
)

func oddPrimes(n uint64) (sieve []uint8) {
    sieve = make([]uint8, (n+1)/2)
    sieve[0] = notprime
    p := uint64(3)
    for i := p * p; i <= n; i = p * p {
        for j := i; j <= n; j += 2 * p {
            sieve[j/2] = notprime
        }
        for p += 2; sieve[p/2] == notprime; p += 2 {
        }
    }
    return sieve
}

func main() {
    start := time.Now()

    var n uint64 = 2000000 - 1
    sum := uint64(0)
    if n >= 2 {
        sum += 2
    }
    for i, p := range oddPrimes(n) {
        if p == prime {
            sum += 2*uint64(i) + 1
        }
    }
    fmt.Println(sum)

    fmt.Println(time.Since(start))
}

Reference: Sieve of Eratosthenes - Wikipedia