diff --git a/integration_tests/test_math.py b/integration_tests/test_math.py index 051c55f3fe..f2edc32efc 100644 --- a/integration_tests/test_math.py +++ b/integration_tests/test_math.py @@ -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 @@ -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() @@ -75,3 +94,5 @@ def test_fabs(): test_pow() test_fabs() test_ldexp() +test_gcd() +test_lcm() diff --git a/src/runtime/math.py b/src/runtime/math.py index 2929236008..cbd1b94354 100644 --- a/src/runtime/math.py +++ b/src/runtime/math.py @@ -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)