Go Program to Check if a Number Is Prime or Not

1. Introduction

Prime numbers have been a topic of intrigue and study for centuries. By definition, a prime number is a number greater than 1 that has no positive divisors other than 1 and itself. In this post, we'll be developing a Go program to verify if a given number is prime.

2. Program Overview

Our Go program is structured to:

1. Prompt the user to input a number.

2. Analyze if the given number is prime or not.

3. Display the conclusion to the user.

3. Code Program

// Our Go program commences with the declaration of the main package.
package main

// The fmt package is utilized to manage input and output operations.
import "fmt"

// Function to validate if a number is prime.
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
}

// The point of entry for our program is the main function.
func main() {
    var number int

    // The user is urged to input a number.
    fmt.Print("Enter a number to check if it's prime: ")
    fmt.Scan(&number)

    // Depending on the evaluation of the number, an appropriate message is displayed.
    if isPrime(number) {
        fmt.Printf("%d is a prime number.\n", number)
    } else {
        fmt.Printf("%d is not a prime number.\n", number)
    }
}

Output:

Let's say the user inputs the number 17. The output would be:
17 is a prime number.

If the number 9 is given, the result would be:
9 is not a prime number.

4. Step By Step Explanation

1. Package and Import Declarations: The journey starts with package main, denoting our program's onset. We include the fmt package for input and output tasks.

2. Prime Number Validation Function: The function isPrime takes in an integer and returns a boolean value. If the number is less than or equal to 1, it's not prime. Otherwise, it checks if the number has any divisor other than 1 and itself.

3. Variable Declaration: A single integer variable, number, is set up to hold the user's input.

4. Obtaining User Input: A prompt is shown using fmt.Print and the subsequent input is captured with fmt.Scan.

5. Analyzing and Presenting the Outcome: The function isPrime is invoked, and based on its result, a pertinent message is shown.

Comments