In this tutorial, we will learn how to print all prime numbers in a given interval in Go. We will cover the basic concept of prime numbers and implement a function to find and print all prime numbers within a specified range.
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 print all prime numbers in an interval 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
}
func printPrimesInInterval(start, end int) []int {
primes := []int{}
for i := start; i <= end; i++ {
if isPrime(i) {
primes = append(primes, i)
}
}
return primes
}
We can create a function to find and print all prime numbers within a specified range by using a helper function to check for primality.
For example,
isPrime
that takes one parameter n
of type int
and returns a boolean indicating if n
is prime.printPrimesInInterval
that takes two parameters start
and end
of type int
.for
loop to iterate from start
to end
(inclusive).isPrime
function. If true, append it to the slice of prime numbers.printPrimesInInterval
function with sample values 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 printPrimesInInterval(start, end int) []int {
primes := []int{}
for i := start; i <= end; i++ {
if isPrime(i) {
primes = append(primes, i)
}
}
return primes
}
func main() {
// Define the interval
start, end := 10, 50
// Print all prime numbers in the interval
primes := printPrimesInInterval(start, end)
fmt.Printf("Prime numbers between %d and %d are: %v\n", start, end, primes)
}
Prime numbers between 10 and 50 are: [11 13 17 19 23 29 31 37 41 43 47]