Introduction
In this assignment you will implement the famous
Sieve Of Eratosthenes
algorithm for finding prime numbers. You will use goroutines to
implement a pipeline where the iterations of outer loop (testing
individual divisors) run concurrently.
- Make sure you commit and push all your work using coursegit before 22:30 on Friday December 11.
Requirements
- The rubric is available
- Your
sievefunction should pass the following tests
package main
import (
"fmt"
"slices"
"testing"
)
func TestSieveTableDriven(t *testing.T) {
var tests = []struct {
nmax int
want []int
}{
{2, []int{2}},
{3, []int{2,3}},
{5, []int{2,3,5}},
{8, []int{2,3,5,7}},
{17, []int{2,3,5,7,11,13,17}},
{100, []int {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97}},
}
for _, tt := range tests {
testname := fmt.Sprintf("%d", tt.nmax)
t.Run(testname, func(t *testing.T) {
ans := sieve(tt.nmax)
if !slices.Equal(tt.want,ans) {
t.Errorf("got %v, want %v", ans, tt.want)
}
})
}
}
Your code should have complete test coverage
You must use goroutines and channels
Hints
- You are strongly recommended to use range of channels and waitgroups
- You only need to test divisors up to @@math:\sqrt{n}@@. The following function may be useful to avoid messing with floating point.
// Translated from Python example https://en.wikipedia.org/wiki/Integer_square_root
func isqrt(y int) int {
L := 0 // lower bound of the square root
R := y + 1 // upper bound of the square root
for L != R - 1 {
M := (L + R) / 2
if M * M <= y {
L = M
} else {
R = M
}
}
return L
}
- No specific optimizations other than only checking @@math:\sqrt{n}@@ divisors are required.