Skip to content

Commit 0f85101

Browse files
authored
Merge pull request #148 from Smit-create/mod_gcd
Add gcd and lcm math functions
2 parents 844ab29 + e626332 commit 0f85101

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

integration_tests/test_math.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from math import (factorial, isqrt, perm, comb, degrees, radians, exp, pow,
2-
ldexp, fabs)
2+
ldexp, fabs, gcd, lcm)
33
from ltypes import i32, f64
44

55

@@ -65,6 +65,25 @@ def test_fabs():
6565
print(i, j)
6666

6767

68+
def test_gcd():
69+
i: i32
70+
i = gcd(10, 4)
71+
assert i == 2
72+
i = gcd(21, 14)
73+
assert i == 7
74+
i = gcd(21, -12)
75+
assert i == 3
76+
77+
def test_lcm():
78+
i: i32
79+
i = lcm(10, 4)
80+
assert i == 20
81+
i = lcm(21, 14)
82+
assert i == 42
83+
i = lcm(21, -12)
84+
assert i == 84
85+
86+
6887
test_factorial_1()
6988
test_comb()
7089
test_isqrt()
@@ -75,3 +94,5 @@ def test_fabs():
7594
test_pow()
7695
test_fabs()
7796
test_ldexp()
97+
test_gcd()
98+
test_lcm()

src/runtime/math.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,40 @@ def pow(x: f64, y: f64) -> f64:
109109
Return `x` raised to the power `y`.
110110
"""
111111
return x**y
112+
113+
114+
def mod(a: i32, b: i32) -> i32:
115+
"""
116+
Returns a%b
117+
"""
118+
return a - (a//b)*b
119+
120+
121+
def gcd(a: i32, b: i32) -> i32:
122+
"""
123+
Returns greatest common divisor of `a` and `b`
124+
"""
125+
temp: i32
126+
if a < 0:
127+
a = -a
128+
if b < 0:
129+
b = -b
130+
while b != 0:
131+
a = mod(a, b)
132+
temp = a
133+
a = b
134+
b = temp
135+
return a
136+
137+
138+
def lcm(a: i32, b: i32) -> i32:
139+
"""
140+
Returns least common multiple of `a` and `b`
141+
"""
142+
if a < 0:
143+
a = -a
144+
if b < 0:
145+
b = -b
146+
if a*b == 0:
147+
return 0
148+
return (a*b)//gcd(a, b)

0 commit comments

Comments
 (0)