Skip to content

Add gcd and lcm math functions #148

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
Feb 19, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
23 changes: 22 additions & 1 deletion integration_tests/test_math.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from math import (factorial, isqrt, perm, comb, degrees, radians, exp, pow,
ldexp, fabs)
ldexp, fabs, gcd, lcm)
from ltypes import i32, f64


Expand Down Expand Up @@ -65,6 +65,25 @@ def test_fabs():
print(i, j)


def test_gcd():
i: i32
i = gcd(10, 4)
assert i == 2
i = gcd(21, 14)
assert i == 7
i = gcd(21, -12)
assert i == 3

def test_lcm():
i: i32
i = lcm(10, 4)
assert i == 20
i = lcm(21, 14)
assert i == 42
i = lcm(21, -12)
assert i == 84


test_factorial_1()
test_comb()
test_isqrt()
Expand All @@ -75,3 +94,5 @@ def test_fabs():
test_pow()
test_fabs()
test_ldexp()
test_gcd()
test_lcm()
37 changes: 37 additions & 0 deletions src/runtime/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,40 @@ def pow(x: f64, y: f64) -> f64:
Return `x` raised to the power `y`.
"""
return x**y


def mod(a: i32, b: i32) -> i32:
"""
Returns a%b
"""
return a - (a//b)*b


def gcd(a: i32, b: i32) -> i32:
"""
Returns greatest common divisor of `a` and `b`
"""
temp: i32
if a < 0:
a = -a
if b < 0:
b = -b
while b != 0:
a = mod(a, b)
temp = a
a = b
b = temp
return a


def lcm(a: i32, b: i32) -> i32:
"""
Returns least common multiple of `a` and `b`
"""
if a < 0:
a = -a
if b < 0:
b = -b
if a*b == 0:
return 0
return (a*b)//gcd(a, b)