Saturday, January 30, 2016

Go Code to Find GCD / HCF of Two or More Integers


In mathematics, the greatest common divisor (GCD) of two or more integers, when at least one of them is not zero, is the largest positive integer that divides the numbers without a remainder.
                                                                                                                                  --- src: Wikipedia

For example, the GCD of 20 and 25 is 5.

The GCD is also known as the: 
      • Greatest common factor (GCF), 
      • Highest common factor (HCF), 
      • Greatest common measure (GCM), 
      • Highest common divisor (HCD)

Prerequisites to understand the following code:
Code follows:

package main

import "fmt"

func main() {

 var n int
 var num int
 var result int

 fmt.Println("How many integers GCD do you want to calculate?")
 fmt.Scanf("%d\n", &n)
 fmt.Println("Enter space separated integers:")
 numList := map[int]int{}

 for i := 1; i <= n; i++ {
  fmt.Scanf("%d", &num)
  numList[i] = num
 }
 //This is the result for only 2 integers
 result = gcd(numList[1], numList[2])

 //for loop in case there're more than 2 ints
 for j := 3; j <= n; j++ {
  result = gcd(result, numList[j])
 }

 fmt.Println("The GCD/HCF of given integers is: ", result)
}

//Func to implement Euclid Algo
func gcd(x, y int) int {
 for y != 0 {
  x, y = y, x%y
 }
 return x
}

Output



Play with the above code

Please share your feedback for improvement of this code.

No comments:

Post a Comment