This program calculates nth prime in golang
primes.go
974 B
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
package main
import (
"log"
"math"
"time"
)
func main() {
for i, v := range []int{25000, 50000, 100000, 1000000} {
start := time.Now()
num := countPrimes(v)
elapsed := time.Since(start)
log.Printf("Test %d: %dth prime is %v \t took %s", i+1, v, num, elapsed)
}
}
func countPrimes(limit int) int {
primes := make([]int, limit)
count := 0
isPrimeDivisible := func(candidate int) bool {
for j := 0; j < count; j++ {
if math.Sqrt(float64(candidate)) < float64(primes[j]) {
return false
}
isDivisibe := isDivisible(candidate, primes[j])
if isDivisibe {
return true
}
}
return false
}
for candidate := 2; ; {
if count < limit {
if !isPrimeDivisible(candidate) {
primes[count] = candidate
count++
}
candidate++
} else {
break
}
}
return primes[limit-1]
}
func isDivisible(candidate, by int) bool {
return candidate%by == 0
}