Skip to content

Instantly share code, notes, and snippets.

@jzacsh
Created October 3, 2017 20:49
Show Gist options
  • Select an option

  • Save jzacsh/fe6c3e63450916de24b0adc0186cb36b to your computer and use it in GitHub Desktop.

Select an option

Save jzacsh/fe6c3e63450916de24b0adc0186cb36b to your computer and use it in GitHub Desktop.
GCD Calculator: Euclidean Algorithm visualizer
package main
import (
"fmt"
)
func gcd(a, b uint64) uint64 {
if a == 0 || b == 0 {
panic(fmt.Errorf("require non-zero natural numbers, but got: %d, %d", a, b))
}
if a == b {
return a
}
var r uint64
bigger := a
smaller := b
if a < b {
bigger = b
smaller = a
}
for (bigger % smaller) != 0 {
r = bigger % smaller
fmt.Printf("\t%5d = %5d x (%5d) + %5d\n", bigger, smaller, bigger/smaller, r)
bigger = smaller
smaller = r
}
return r
}
func main() {
givens := [][]uint64{{81, 57}, {103927, 102313}}
for _, pair := range givens {
result := gcd(pair[0], pair[1])
fmt.Printf("... so gcd of %d and %d is %d\n\n", pair[0], pair[1], result)
}
}
@jzacsh
Copy link
Copy Markdown
Author

jzacsh commented Oct 3, 2017

Live here https://play.golang.org/p/2qIawSsEb6 for showing someone golang

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment