Exemple #1
0
func TestSieve(t *testing.T) {
	cases := []struct {
		n    int // input to Sieve(n)
		want int // expected largest prime <= n (0 if it does not exist)
	}{
		{-1, 0},
		{0, 0},
		{1, 0},
		{2, 2},
		{3, 3},
		{4, 3},
		{1229, 1229},
		{100, 97},
		{1000, 997},
		{10000, 9973},
		{100000, 99991},
		{200000, 199999},
		{500000, 499979},
		{1000000, 999983},
	}
	for _, c := range cases {
		ps := primes.Sieve(c.n)
		if c.want > 0 {
			if len(ps) == 0 {
				t.Errorf("Sieve(%d) == [], want something", c.n)
			} else if last := ps[len(ps)-1]; last != c.want {
				t.Errorf("Sieve(%d)[-1] == %d, want %d", c.n, last, c.want)
			}
		} else {
			if l := len(ps); l > 0 {
				t.Errorf("|Sieve(%d)| == %d, want 0", c.n, l)
			}
		}
	}
}
Exemple #2
0
func ExampleSieve() {
	// Generate the prime numbers less than or equal to 20
	ps := primes.Sieve(20)
	fmt.Println(ps)

	// Output: [2 3 5 7 11 13 17 19]
}
Exemple #3
0
func TestSieveAgainstBaseline(t *testing.T) {
	ns := []int{0, 1, 2, 3, 10000000}
	for _, n := range ns {
		ps := primes.Sieve(n)
		qs := baselineSieve(n)
		if len(ps) != len(qs) {
			t.Errorf("SieveAgainstBaseline(%d): len == %d, want %d", n, len(ps), len(qs))
			break
		}
		for i, p := range ps {
			if p != qs[i] {
				t.Errorf("SieveAgainstBaseline(%d): [%d] == %d, want %d", n, i, p, qs[i])
				break
			}
		}
	}
}