Esempio n. 1
0
func TestPi(t *testing.T) {
	cases := []struct {
		n    int
		want int
	}{
		{10, 4},
		{100, 25},
		{1000, 168},
		{10000, 1229},
		{100000, 9592},
		{1000000, 78498},
		{10000000, 664579},
		{100000000, 5761455},
		{1000000000, 50847534},
		{104730, 10000},
	}
	// Maximum relative error when Pi(n) returns an estimate
	const epsMax = 0.01
	for _, c := range cases {
		pi, ok := primes.Pi(c.n)
		if ok {
			if pi != c.want {
				t.Errorf("Pi(%d) == (%d,true), want %d", c.n, pi, c.want)
			}
		} else {
			eps := math.Abs(float64(pi-c.want) / float64(c.want))
			if eps >= epsMax {
				t.Errorf("Pi(%d) == (%d,false), want %d; eps=%f", c.n, pi, c.want, eps)
			}
		}

	}
}
Esempio n. 2
0
func ExamplePi() {
	// Check how many prime numbers are less than or equal to n
	ns := []int{6, 11, 23, 12345}
	for _, n := range ns {
		pi, ok := primes.Pi(n)
		if ok {
			fmt.Printf("There are %d primes in [0,%d]\n", pi, n)
		} else {
			fmt.Printf("There are approximately %d primes in [0,%d]\n", pi, n)
		}
	}

	// Output:
	// There are 3 primes in [0,6]
	// There are 5 primes in [0,11]
	// There are 9 primes in [0,23]
	// There are approximately 1465 primes in [0,12345]
}