In this tutorial, we will learn how to check if a number is a prime number in Go. We will cover the basic concept of prime numbers and implement a function to perform the check.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This means that a prime number cannot be formed by multiplying two smaller natural numbers.
The syntax to check if a number is prime in Go is:
func isPrime(n int) bool {
if n <= 1 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
We can create a function to check if a given number is a prime number by testing its divisors.
For example,
isPrime
that takes one parameter n
of type int
.n
is less than or equal to 1. If true, return false
.for
loop to iterate from 2 to the square root of n
(inclusive).n
is divisible by any of the values in the loop. If true, return false
.true
.isPrime
function with sample numbers and print the results.package main
import (
"fmt"
)
func isPrime(n int) bool {
if n <= 1 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
func main() {
// Sample numbers
numbers := []int{2, 4, 7, 10, 13}
// Check and print if each number is a prime number
for _, number := range numbers {
result := isPrime(number)
if result {
fmt.Printf("%d is a prime number\n", number)
} else {
fmt.Printf("%d is not a prime number\n", number)
}
}
}
2 is a prime number 4 is not a prime number 7 is a prime number 10 is not a prime number 13 is a prime number