Print all Prime Numbers in an Interval in Go
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.
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 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
}
Example 1: Printing all prime numbers in an interval
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,
- Define a helper function named
isPrime
that takes one parametern
of typeint
and returns a boolean indicating ifn
is prime. - Define a function named
printPrimesInInterval
that takes two parametersstart
andend
of typeint
. - Initialize an empty slice to store the prime numbers.
- Use a
for
loop to iterate fromstart
toend
(inclusive). - For each number in the loop, check if it is prime using the
isPrime
function. If true, append it to the slice of prime numbers. - Return the slice of prime numbers.
- In the main function, call the
printPrimesInInterval
function with sample values 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 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)
}
Output
Prime numbers between 10 and 50 are: [11 13 17 19 23 29 31 37 41 43 47]