Check Prime Number in Go
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.
What is a Prime Number
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.
Syntax
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
}
Example 1: Checking if a number is a prime number
We can create a function to check if a given number is a prime number by testing its divisors.
For example,
- Define a function named
isPrime
that takes one parametern
of typeint
. - Check if
n
is less than or equal to 1. If true, returnfalse
. - Use a
for
loop to iterate from 2 to the square root ofn
(inclusive). - Check if
n
is divisible by any of the values in the loop. If true, returnfalse
. - If the loop completes without finding any divisors, return
true
. - In the main function, call the
isPrime
function with sample numbers and print the results.
Go Program
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)
}
}
}
Output
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