checking for prime numbers using golang

package main

import (
    "fmt"
)

func isPrime(num int) bool {
    if num <= 1 {
        return false
    }
    for i := 2; i*i <= num; i++ {
        if num%i == 0 {
            return false
        }
    }
    return true
}

func main() {
    fmt.Println("Prime numbers between 1 and 20:")
    for i := 1; i <= 20; i++ {
        if isPrime(i) {
            fmt.Println(i)
        }
    }
}

Explanation:

  1. package main: Declares that this file is part of the main package in Go.

  2. import "fmt": Imports the "fmt" package, which provides functions for formatting input and output.

  3. func isPrime(num int) bool: Defines a function named isPrime that takes an integer num as input and returns a boolean value (true if the number is prime, false otherwise).

  4. if num <= 1 { return false }: Checks if the input number is less than or equal to 1. If so, returns false as prime numbers are greater than 1.

  5. for i := 2; i*i <= num; i++: Iterates from 2 to the square root of the input number (num) using the variable i. This loop checks divisibility only up to the square root of num to optimize the algorithm.

  6. if num%i == 0 { return false }: Checks if the input number (num) is divisible by the current value of i. If it is divisible, returns false as it indicates that the number is not prime.

  7. return true: If no divisors are found in the loop, the number is prime, so the function returns true.

  8. func main(): Defines the main function where the execution of the program starts.

  9. fmt.Println("Prime numbers between 1 and 20:"): Prints a message indicating the prime numbers will be displayed between 1 and 20.

  10. for i := 1; i <= 20; i++ { if isPrime(i) { fmt.Println(i) } }: Iterates through numbers from 1 to 20. For each number, it checks if it is prime using the isPrime function and prints the number if it's prime.