Esempio n. 1
0
func TestIsPrime(t *testing.T) {
	// Check a few simple cases
	cases := []struct {
		n    int
		want bool
	}{
		{-1, false},
		{0, false},
		{1, false},
		{2, true},
		{3, true},
		{6, false},
		{1000003, true},
		{1000037, true},
	}
	for _, c := range cases {
		p := primes.IsPrime(c.n)
		if p != c.want {
			t.Errorf("IsPrime(%d) == %v, want %v", c.n, p, c.want)
		}
	}

	// Check against each continguous sequence of primes that the primes
	// are classified as primes and the numbers in between as not.
	contiguousPrimes := [][]int{
		{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47},
		{127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181},
		{877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953},
		{2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153},
		{9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931},
		{1000003, 1000033, 1000037},
	}
	for _, ps := range contiguousPrimes {
		for _, p := range ps {
			if !primes.IsPrime(p) {
				t.Errorf("IsPrime(%d) == false, want true", p)
			}
		}
		for i := 1; i < len(ps); i++ {
			for n := ps[i-1] + 1; n < ps[i]; n++ {
				if primes.IsPrime(n) {
					t.Errorf("IsPrime(%d) == true, want false", n)
				}
			}
		}
	}

	// Check that the numbers obtain by multiplying any two of the following
	// prime factors are classified as not primes
	factors := []int{2, 3, 41, 157, 953, 2141, 9929}
	for i, p := range factors {
		for j := 0; j <= i; j++ {
			q := factors[j]
			n := p * q
			if primes.IsPrime(n) {
				t.Errorf("IsPrime(%d) == true, want false", n)
			}
		}
	}
}
Esempio n. 2
0
func TestIsPrimeAgainstBaseline(t *testing.T) {
	for n := -1; n < 1000; n++ {
		p := primes.IsPrime(n)
		q := baselineIsPrime(n)
		if p != q {
			t.Errorf("IsPrimeAgainstBaseline(%d) == %v, want %v", n, p, q)
		}
	}
	for i := 0; i < 10000; i++ {
		n := rand.Intn(math.MaxInt32)
		p := primes.IsPrime(n)
		q := baselineIsPrime(n)
		if p != q {
			t.Errorf("IsPrimeAgainstBaseline(%d) == %v, want %v", n, p, q)
		}
	}
}
Esempio n. 3
0
func ExampleIsPrime() {
	// Check which numbers are prime
	ns := []int{2, 23, 49, 73, 98765, 1000003, 10007 * 10009, math.MaxInt32}
	for _, n := range ns {
		if primes.IsPrime(n) {
			fmt.Printf("%d is prime\n", n)
		} else {
			fmt.Printf("%d is composite\n", n)
		}
	}

	// Output:
	// 2 is prime
	// 23 is prime
	// 49 is composite
	// 73 is prime
	// 98765 is composite
	// 1000003 is prime
	// 100160063 is composite
	// 2147483647 is prime
}