32 lines
601 B
Go
32 lines
601 B
Go
package prime
|
|
|
|
var sieve []int
|
|
|
|
// Nth finds the nth prime and 'true' if the 0th prime wasn't requested
|
|
func Nth(n int) (int, bool) {
|
|
if n == 0 {
|
|
return 0, false
|
|
}
|
|
if len(sieve) == 0 {
|
|
// Let's just do some initialization
|
|
sieve = append(sieve, 0)
|
|
sieve = append(sieve, 2)
|
|
}
|
|
sieveLen := len(sieve)
|
|
for i := sieve[len(sieve)-1]; sieveLen <= n; i++ {
|
|
isPrime := true
|
|
for j := 1; j < sieveLen; j++ {
|
|
if i%sieve[j] == 0 {
|
|
isPrime = false
|
|
break
|
|
}
|
|
}
|
|
if isPrime {
|
|
// Found a new prime
|
|
sieve = append(sieve, i)
|
|
sieveLen = len(sieve)
|
|
}
|
|
}
|
|
return sieve[n], true
|
|
}
|