This commit is contained in:
2016-08-29 22:24:05 -05:00
parent e63233cad7
commit 36dc090a89
6 changed files with 115 additions and 23 deletions

27
go/nth-prime/README.md Normal file
View File

@@ -0,0 +1,27 @@
# Nth Prime
Write a program that can tell you what the nth prime is.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that
the 6th prime is 13.
If your language provides methods in the standard library to deal with prime
numbers, pretend they don't exist and implement them yourself.
To run the tests simply run the command `go test` in the exercise directory.
If the test suite contains benchmarks, you can run these with the `-bench`
flag:
go test -bench .
For more detailed info about the Go track see the [help
page](http://exercism.io/languages/go).
## Source
A variation on Problem 7 at Project Euler [http://projecteuler.net/problem=7](http://projecteuler.net/problem=7)
## Submitting Incomplete Problems
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

33
go/nth-prime/nth_prime.go Normal file
View File

@@ -0,0 +1,33 @@
package prime
var sieve []int
func Nth(n int) (int, bool) {
if len(sieve) == 0 {
sieve = append(sieve, 0)
sieve = append(sieve, 2)
}
if n == 0 {
return 0, false
}
for i := sieve[len(sieve)-1]; n <= len(sieve); i++ {
// Check if i is a prime
isPrime := true
for j := 1; j < len(sieve); j++ {
if i%sieve[j] == 0 {
// Not a prime
isPrime = false
break
}
}
if isPrime {
// Found a new prime
sieve = append(sieve, i)
if len(sieve) >= n {
break
}
}
}
return sieve[n], true
}

View File

@@ -0,0 +1,39 @@
package prime
import "testing"
var tests = []struct {
n int
p int
ok bool
}{
{1, 2, true},
{2, 3, true},
{3, 5, true},
{4, 7, true},
{5, 11, true},
{6, 13, true},
{10001, 104743, true},
{0, 0, false},
}
func TestNth(t *testing.T) {
for _, test := range tests {
switch p, ok := Nth(test.n); {
case !ok:
if test.ok {
t.Fatalf("Nth(%d) returned !ok. Expecting ok.", test.n)
}
case !test.ok:
t.Fatalf("Nth(%d) = %d, ok = %t. Expecting !ok.", test.n, p, ok)
case p != test.p:
t.Fatalf("Nth(%d) = %d, want %d.", test.n, p, test.p)
}
}
}
func BenchmarkNth(b *testing.B) {
for i := 0; i < b.N; i++ {
Nth(10001)
}
}