Skip to content

Commit 95d4b1e

Browse files
committed
Merge branch 'feature/gcd' into develop
2 parents 097f987 + 27e45f9 commit 95d4b1e

File tree

4 files changed

+49
-21
lines changed

4 files changed

+49
-21
lines changed

go-algorithm/internal/math/gcd.go

-9
This file was deleted.

go-algorithm/internal/math/gcd_test.go

-12
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package math
2+
3+
type GCD interface {
4+
gcd(a int, b int) int
5+
gcdExtended(a int, b int) (int, int, int)
6+
}
7+
8+
type NumberTuple struct {
9+
a int // dividend
10+
b int // divisor
11+
}
12+
13+
// GCD finds the greatest common divisor of two numbers.
14+
func (n NumberTuple) gcd() int {
15+
for n.b != 0 {
16+
n.a, n.b = n.b, n.a%n.b
17+
}
18+
return n.a
19+
}
20+
21+
// GCDExtended finds the greatest common divisor of two numbers with extended Euclidean algorithm.
22+
func (n NumberTuple) gcdExtended() (int, int, int) {
23+
if n.b == 0 {
24+
return n.a, 1, 0
25+
}
26+
d, x, y := NumberTuple{n.b, n.a % n.b}.gcdExtended()
27+
return d, y, x - (n.a/n.b)*y
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package math
2+
3+
import (
4+
"github.com/stretchr/testify/assert"
5+
"testing"
6+
)
7+
8+
func TestGCD(t *testing.T) {
9+
assert.Equal(t, 12, NumberTuple{24, 36}.gcd())
10+
assert.Equal(t, 1, NumberTuple{17, 22}.gcd())
11+
assert.Equal(t, 20, NumberTuple{120, 500}.gcd())
12+
}
13+
14+
func TestGCDExtended(t *testing.T) {
15+
d1, _, _ := NumberTuple{24, 36}.gcdExtended()
16+
assert.Equal(t, 12, d1)
17+
d2, _, _ := NumberTuple{17, 22}.gcdExtended()
18+
assert.Equal(t, 1, d2)
19+
d3, _, _ := NumberTuple{120, 500}.gcdExtended()
20+
assert.Equal(t, 20, d3)
21+
}

0 commit comments

Comments
 (0)