diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 57640d2d6..04ec1f0fd 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,3 +8,4 @@ Hitesh C Maxime Dherbécourt Jess 3Jane Pen Pal +Chinmaya Mahesh diff --git a/chapters/euclidean_algorithm/code/go/euclidean.go b/chapters/euclidean_algorithm/code/go/euclidean.go new file mode 100644 index 000000000..f457b1849 --- /dev/null +++ b/chapters/euclidean_algorithm/code/go/euclidean.go @@ -0,0 +1,46 @@ +// Submitted by Chinmaya Mahesh (chin123) + +package main + +import "fmt" + +func abs(a int) int { + if a < 0 { + a = -a + } + return a +} + +func euclidMod(a, b int) int { + a = abs(a) + b = abs(b) + + for b != 0 { + a, b = b, a%b + } + + return a +} + +func euclidSub(a, b int) int { + a = abs(a) + b = abs(b) + + for a != b { + if a > b { + a -= b + } else { + b -= a + } + } + + return a +} + +func main() { + check1 := euclidMod(64*67, 64*81) + check2 := euclidSub(128*12, 128*77) + + fmt.Println(check1) + fmt.Println(check2) +} diff --git a/chapters/euclidean_algorithm/euclidean.md b/chapters/euclidean_algorithm/euclidean.md index bfa0dc432..423a553cd 100644 --- a/chapters/euclidean_algorithm/euclidean.md +++ b/chapters/euclidean_algorithm/euclidean.md @@ -25,6 +25,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:9-17, lang="ocaml"](code/ocaml/euclidean_example.ml) {% sample lang="java" %} [import:9-22, lang="java"](code/java/euclidean_example.java) +{% sample lang="go" %} +[import:25-38, lang="go"](code/go/euclidean.go) {% endmethod %} Here, we simply line the two numbers up every step and subtract the lower value from the higher one every timestep. Once the two values are equal, we call that value the greatest common divisor. A graph of `a` and `b` as they change every step would look something like this: @@ -56,6 +58,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:3-7, lang="ocaml"](code/ocaml/euclidean_example.ml) {% sample lang="java" %} [import:24-35, lang="java"](code/java/euclidean_example.java) +{% sample lang="go" %} +[import:14-23, lang="go"](code/go/euclidean.go) {% endmethod %} Here, we set `b` to be the remainder of `a%b` and `a` to be whatever `b` was last timestep. Because of how the modulus operator works, this will provide the same information as the subtraction-based implementation, but when we show `a` and `b` as they change with time, we can see that it might take many fewer steps: @@ -102,6 +106,9 @@ Program.cs {% sample lang="java" %} ### Java [import, lang="java"](code/java/euclidean_example.java) +{% sample lang="go" %} +### Go +[import, lang="go"](code/go/euclidean.go) {% endmethod %}