2016-08-30 03:24:05 +00:00
|
|
|
package prime
|
|
|
|
|
|
|
|
var sieve []int
|
|
|
|
|
2016-09-02 19:26:22 +00:00
|
|
|
// Nth finds the nth prime and 'true' if the 0th prime wasn't requested
|
2016-08-30 03:24:05 +00:00
|
|
|
func Nth(n int) (int, bool) {
|
2016-09-02 19:26:22 +00:00
|
|
|
if n == 0 {
|
|
|
|
return 0, false
|
|
|
|
}
|
2016-08-30 03:24:05 +00:00
|
|
|
if len(sieve) == 0 {
|
2016-09-02 19:26:22 +00:00
|
|
|
// Let's just do some initialization
|
2016-08-30 03:24:05 +00:00
|
|
|
sieve = append(sieve, 0)
|
|
|
|
sieve = append(sieve, 2)
|
|
|
|
}
|
2016-09-02 19:26:22 +00:00
|
|
|
sieveLen := len(sieve)
|
|
|
|
for i := sieve[len(sieve)-1]; sieveLen <= n; i++ {
|
2016-08-30 03:24:05 +00:00
|
|
|
isPrime := true
|
2016-09-02 19:26:22 +00:00
|
|
|
for j := 1; j < sieveLen; j++ {
|
2016-08-30 03:24:05 +00:00
|
|
|
if i%sieve[j] == 0 {
|
|
|
|
isPrime = false
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if isPrime {
|
|
|
|
// Found a new prime
|
|
|
|
sieve = append(sieve, i)
|
2016-09-02 19:26:22 +00:00
|
|
|
sieveLen = len(sieve)
|
2016-08-30 03:24:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return sieve[n], true
|
|
|
|
}
|