Go Program to Find the GCD of Two Numbers

1. Introduction

The Greatest Common Divisor (GCD) is the largest positive integer that divides two or more numbers without leaving a remainder. Finding the GCD is fundamental in number theory and has practical applications in fields like cryptography. In this tutorial, we'll learn how to create a Go program that calculates the GCD of two given numbers.

2. Program Overview

Our Go program will:

1. Prompt the user to input two numbers.

2. Compute the GCD of the provided numbers.

3. Showcase the calculated GCD to the user.

3. Code Program

// We kickstart our Go program with the declaration of the main package.
package main

// The fmt package is brought in to manage input and output tasks.
import "fmt"

// Function to compute the GCD using the Euclidean algorithm.
func findGCD(a, b int) int {
    for b != 0 {
        a, b = b, a%b
    }
    return a
}

// The main function signifies the entry point of our program.
func main() {
    var num1, num2 int

    // We ask the user to provide two numbers.
    fmt.Print("Enter the first number: ")
    fmt.Scan(&num1)
    fmt.Print("Enter the second number: ")
    fmt.Scan(&num2)

    // The GCD of the numbers is computed and displayed.
    fmt.Printf("The GCD of %d and %d is: %d\n", num1, num2, findGCD(num1, num2))
}

Output:

For instance, if a user inputs the numbers 56 and 98, the program's output will be:
The GCD of 56 and 98 is: 14

4. Step By Step Explanation

1. Package and Import Statements: We begin with package main, denoting the start of our program. The fmt package is essential for handling I/O operations.

2. GCD Calculation Function: The findGCD function employs the Euclidean algorithm, a widely recognized method for computing the GCD. The algorithm iteratively reduces the problem of finding the GCD of two numbers into smaller instances of the same problem.

3. Variable Declaration: Two integer variables, num1 and num2, are initialized to collect user inputs.

4. Gathering User Inputs and Displaying Result: Users are prompted to enter two numbers. Subsequently, the GCD is computed and revealed using the findGCD function.

Comments