exercism/go/nth-prime/nth_prime.go

32 lines
601 B
Go
Raw Normal View History

2016-08-30 03:24:05 +00:00
package prime
var sieve []int
// 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) {
if n == 0 {
return 0, false
}
2016-08-30 03:24:05 +00:00
if len(sieve) == 0 {
// Let's just do some initialization
2016-08-30 03:24:05 +00:00
sieve = append(sieve, 0)
sieve = append(sieve, 2)
}
sieveLen := len(sieve)
for i := sieve[len(sieve)-1]; sieveLen <= n; i++ {
2016-08-30 03:24:05 +00:00
isPrime := true
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)
sieveLen = len(sieve)
2016-08-30 03:24:05 +00:00
}
}
return sieve[n], true
}