Prime Number Sample CodeΒΆ
Here are some simple functions are finding prime numbers. These are meant as examples of basic Go programming. An example of table-driven testing is included, a popular testing technique in the Go community.
// primes.go
package main
import (
"fmt"
)
func isPrime(n int) bool {
if n < 2 {
return false
} else if n == 2 {
return true
} else if n%2 == 0 {
return false
} else { // n > 2
d := 3
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
} // for
return true
} // if
}
func isPrime2(n int) bool {
switch {
case n < 2:
return false
case n == 2:
return true
case n%2 == 0:
return false
default: // n > 2
d := 3
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
} // for
return true
} // switch
}
//
// table-driven testing
//
var prime = []int{2, 3, 5, 7, 11, 13, 17, 31, 37, 101}
var notPrime = []int{-2, -1, 0, 1, 4, 6, 8, 9, 10, 12, 91, 100}
func testIsPrime(isPrime func(int) bool) {
for _, n := range prime {
if !isPrime(n) {
fmt.Printf("testIsPrime: %v is prime!\n", n)
panic("error!")
}
}
for _, n := range notPrime {
if isPrime(n) {
fmt.Printf("testIsPrime: %v is not prime!\n", n)
panic("error!")
}
}
fmt.Println("all testIsPrime tests passed")
}
func countPrimesLessThan(n int) (count int) {
if n < 2 {
return 0
} else {
for i := 2; i < n; i++ {
if isPrime(i) {
count++
}
}
return count
}
}
func main() {
testIsPrime(isPrime)
testIsPrime(isPrime2)
// nvals := []int{10, 100, 1000, 10000, 100000}
// for _, n := range nvals {
// fmt.Printf("countPrimesLessThan(%v)=%v\n", n, countPrimesLessThan(n))
// }
// for i := 0; i < len(nvals); i++ {
// fmt.Printf("countPrimesLessThan(%v)=%v\n", nvals[i], countPrimesLessThan(nvals[i]))
// }
// for i := 0; i <= 25; i++ {
// fmt.Printf("isPrime2(%v) = %v\n", i, isPrime2(i))
// }
} // main