UNB/ CS/ David Bremner/ teaching/ cs2613/ assignments/ CS2613 Assignment 5

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.

Requirements

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)
                        }
                })
        }
}

Hints

// 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
}