Go Tutorials

Go Programs

Go Print all Prime Numbers in an Interval


Go Print all Prime Numbers in an Interval

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
}


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,

  1. Define a helper function named isPrime that takes one parameter n of type int and returns a boolean indicating if n is prime.
  2. Define a function named printPrimesInInterval that takes two parameters start and end of type int.
  3. Initialize an empty slice to store the prime numbers.
  4. Use a for loop to iterate from start to end (inclusive).
  5. 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.
  6. Return the slice of prime numbers.
  7. 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]