To implement basic number theory algorithms like prime factorization and prime checking in Go, you can use the following code snippets:
Prime Checking:
package main
import (
"fmt"
"math"
)
func isPrime(n int) bool {
if n <= 1 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}
func main() {
fmt.Println(isPrime(11)) // Output: true
fmt.Println(isPrime(12)) // Output: false
}
Prime Factorization:
package main
import (
"fmt"
)
func primeFactorization(n int) []int {
factors := []int{}
for i := 2; i <= n; i++ {
for n%i == 0 {
factors = append(factors, i)
n /= i
}
}
return factors
}
func main() {
fmt.Println(primeFactorization(24)) // Output: [2 2 2 3]
fmt.Println(primeFactorization(33)) // Output: [3 11]
}
You can run these snippets in a Go file (main.go
) and execute them using the go run
command in your terminal:
$ go run main.go