Skip to content

Commit c899a43

Browse files
committed
feat: introduce function to find gcd of 2 numbers
1 parent 890297e commit c899a43

3 files changed

Lines changed: 33 additions & 0 deletions

File tree

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
- [Abs](math/abs.jule)
55
- [Fact](math/fact.jule)
66
- [Fib](math/fib.jule)
7+
- [Gcd](math/gcd.jule)
78
- [Max](math/max.jule)
89
- [Median](math/median.jule)
910
- [Min](math/min.jule)

math/gcd.jule

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
fn Gcd(a: int, b: int): int {
2+
let mut x = a
3+
let mut y = b
4+
5+
if x < 0 {
6+
x = -x
7+
}
8+
if y < 0 {
9+
y = -y
10+
}
11+
12+
for y != 0 {
13+
let t = x % y
14+
x = y
15+
y = t
16+
}
17+
return x
18+
}

math/gcd_test.jule

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#build test
2+
3+
use "std/testing"
4+
5+
#test
6+
fn testGcd(t: &testing::T) {
7+
t.Assert(Gcd(54, 24) == 6, "gcd(54, 24) should be 6")
8+
t.Assert(Gcd(48, 18) == 6, "gcd(48, 18) should be 6")
9+
t.Assert(Gcd(17, 13) == 1, "gcd(17, 13) should be 1")
10+
t.Assert(Gcd(0, 0) == 0, "gcd(0, 0) should be 0")
11+
t.Assert(Gcd(0, 5) == 5, "gcd(0, 5) should be 5")
12+
t.Assert(Gcd(-12, 18) == 6, "gcd(-12, 18) should be 6")
13+
t.Assert(Gcd(12, -18) == 6, "gcd(12, -18) should be 6")
14+
}

0 commit comments

Comments
 (0)