Introduction
In mathematics, the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM) are two important concepts related to integers.
The GCD of two numbers is the largest number that divides both of them without leaving a remainder. The LCM of two numbers is the smallest number that is divisible by both of them.
This program demonstrates how to calculate the GCD and LCM of two numbers using the Euclidean algorithm for GCD and the relationship between GCD and LCM for LCM calculation.
Objective
The objective of this program is to compute the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM) for two given numbers. The user will input two integers, and the program will display their GCD and LCM values.
Go Code
package main import "fmt" // Function to compute the GCD of two numbers func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) } // Function to compute the LCM of two numbers func lcm(a, b int) int { return (a * b) / gcd(a, b) } func main() { var num1, num2 int // Taking input from the user fmt.Print("Enter the first number: ") fmt.Scan(&num1) fmt.Print("Enter the second number: ") fmt.Scan(&num2) // Calculating GCD and LCM resultGCD := gcd(num1, num2) resultLCM := lcm(num1, num2) // Displaying the results fmt.Printf("The GCD of %d and %d is: %d\n", num1, num2, resultGCD) fmt.Printf("The LCM of %d and %d is: %d\n", num1, num2, resultLCM) }
Explanation of the Program
The program is divided into three main parts:
- gcd Function: This function uses the Euclidean algorithm to compute the Greatest Common Divisor of two numbers. It recursively calls itself with the second number and the remainder of the division until the remainder is zero. The GCD is the first number when the remainder becomes zero.
- lcm Function: This function calculates the Least Common Multiple using the formula: LCM(a, b) = (a * b) / GCD(a, b).
- main Function: This function takes two integers as input from the user, calls the gcd and lcm functions to compute the results, and then prints the results on the screen.
How to Run the Program
- Install the Go programming language on your machine if it’s not already installed. You can download it from the official Go website: Go Downloads.
- Save the code in a file with a
.go
extension (e.g.,gcd_lcm.go
). - Open a terminal or command prompt and navigate to the directory where the Go file is saved.
- Run the following command to execute the program:
go run gcd_lcm.go
- Enter two integers when prompted, and the program will output their GCD and LCM values.