Find HCF or GCD in Go
In this tutorial, we will learn how to find the Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two numbers in Go. We will cover the basic concept and implement functions using both the math library and the Euclidean algorithm.
What is HCF or GCD
The Highest Common Factor (HCF) or Greatest Common Divisor (GCD) of two or more integers is the largest positive integer that divides each of the integers without leaving a remainder. For example, the HCF/GCD of 8 and 12 is 4.
Syntax
The syntax to find the HCF or GCD of two numbers in Go can be done in two ways:
import (
"fmt"
"math"
)
func gcdUsingMath(a, b int) int {
return int(math.Gcd(float64(a), float64(b)))
}
func gcdUsingEuclidean(a, b int) int {
for b != 0 {
a, b = b, a % b
}
return a
}Example 1: Finding the HCF or GCD of two numbers using the math library
We can use the built-in math library in Go to find the HCF or GCD of two numbers.
For example,
- Import the
fmtandmathpackages. - Define a function named
gcdUsingMaththat takes two parametersaandbof typeint. - Use the
math.Gcdfunction to find the HCF or GCD of the two numbers. - Return the result as an integer.
- In the main function, call the
gcdUsingMathfunction with sample values and print the result.
Go Program
package main
import (
"fmt"
"math"
)
func gcdUsingMath(a, b int) int {
return int(math.Gcd(float64(a), float64(b)))
}
func main() {
// Find the HCF/GCD of 8 and 12 using the math library
result := gcdUsingMath(8, 12)
// Print the result
fmt.Printf("HCF/GCD of 8 and 12 using math library is %d\n", result)
}Output
HCF/GCD of 8 and 12 using math library is 4
Example 2: Finding the HCF or GCD of two numbers using the Euclidean algorithm
We can use the Euclidean algorithm to find the HCF or GCD of two numbers by iterating through the modulo operation.
For example,
- Define a function named
gcdUsingEuclideanthat takes two parametersaandbof typeint. - Use a
forloop to iterate untilbbecomes zero. - In each iteration, set
atobandbtoa % b. - Return the value of
aafter the loop ends. - In the main function, call the
gcdUsingEuclideanfunction with sample values and print the result.
Go Program
package main
import (
"fmt"
)
func gcdUsingEuclidean(a, b int) int {
for b != 0 {
a, b = b, a % b
}
return a
}
func main() {
// Find the HCF/GCD of 8 and 12 using the Euclidean algorithm
result := gcdUsingEuclidean(8, 12)
// Print the result
fmt.Printf("HCF/GCD of 8 and 12 using Euclidean algorithm is %d\n", result)
}Output
HCF/GCD of 8 and 12 using Euclidean algorithm is 4