-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsummationOfPrimes2.go
50 lines (44 loc) · 1.02 KB
/
summationOfPrimes2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"fmt"
)
func SieveOfEratosthenes(n int64) []int64 {
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
integers := make([]bool, n+1)
for i := int64(2); i < n+1; i++ {
integers[i] = true
}
for p := int64(2); p*p <= n; p++ {
// If integers[p] is not changed, then it is a prime
if integers[p] == true {
// Update all multiples of p
for i := p * 2; i <= n; i += p {
integers[i] = false
}
}
}
// return all prime numbers <= n
var primes []int64
for p := int64(2); p <= n; p++ {
if integers[p] == true {
primes = append(primes, p)
}
}
return primes
}
func main() {
primes := SieveOfEratosthenes(2000000)
fmt.Printf("There are %v primes till two million", len(primes))
sum := int64(0)
for _, prime := range primes {
sum1 := sum + prime
if sum1 < sum {
fmt.Println(sum)
} else {
sum = sum1
}
}
fmt.Println("\nSum of all primes till two million:", sum)
}