Created
October 3, 2017 20:49
-
-
Save jzacsh/fe6c3e63450916de24b0adc0186cb36b to your computer and use it in GitHub Desktop.
GCD Calculator: Euclidean Algorithm visualizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live here https://play.golang.org/p/2qIawSsEb6 for showing someone golang