Skip to content

Add euclidean algorithm implementation for Go #160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 29, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ Hitesh C
Maxime Dherbécourt
Jess 3Jane
Pen Pal
Chinmaya Mahesh
46 changes: 46 additions & 0 deletions chapters/euclidean_algorithm/code/go/euclidean.go
Original file line number Diff line number Diff line change
@@ -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)
}
2 changes: 2 additions & 0 deletions chapters/euclidean_algorithm/euclidean.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:7-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:
Expand Down