Skip to content

Commit

Permalink
Add gcd() and lcm() function
Browse files Browse the repository at this point in the history
  • Loading branch information
FourteenBrush committed Nov 15, 2023
1 parent dddd166 commit 49dd638
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static void init(ExecutionEnv env) {
return Math.round(ctx.getDouble(0));
}
double value = ctx.getDouble(0);
int places = ctx.getBoundedInt(1, 0, Integer.MAX_VALUE);
int places = ctx.getInt(1);
double factor = Utility.getPowerOfTen(places);

return Math.round(value * factor) / factor;
Expand All @@ -104,5 +104,15 @@ public static void init(ExecutionEnv env) {
throw new SyntaxException(e.getMessage());
}
});
env.insertFunction("gcd", 2, ctx -> {
int a = ctx.getInt(0);
int b = ctx.getInt(1);
return Utility.gcd(a, b);
});
env.insertFunction("lcm", 2, ctx -> {
int a = ctx.getInt(0);
int b = ctx.getInt(1);
return Utility.lcm(a, b);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,37 @@ public static boolean isValidArgument(int c) {
public static boolean isBetweenBrackets(int c) {
return c != ')';
}

public static int gcd(int a, int b) {
if (a < 0) a = -a;
if (b < 0) b = -b;
if (a < b) { // force a >= b
int tmp = a;
a = b;
b = tmp;
}

while (b != 0) {
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}

private static int fastUnsignedGcd(int a, int b) {
while (b != 0) {
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}

public static int lcm(int a, int b) {
if (b == 0) return 0;
if (a < 0) a = -a;
if (b < 0) b = -b;
return a / fastUnsignedGcd(a, b) * b;
}
}
7 changes: 6 additions & 1 deletion core/src/test/resources/negative-input.csv
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,9 @@ max(0)
"min(1,-.)"
"sin(1,,)"
"sin(1,,2)"
pi1
pi1
gcd()
"gcd(1,)"
"gcd(1.5, 3)"
"gcd(3.5, 1.2)"
"lcm(-3/2, 1)"
21 changes: 21 additions & 0 deletions core/src/test/resources/positive-input.csv
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,24 @@ pi,pi
"xnor(0, 1)",0
"xnor(1, 0)",0
"xnor(1, 1)",1
"gcd(10, 5)",5
"gcd(25, 5)",5
"gcd(30, 15)",15
"gcd(30, 9)",3
"gcd(29, 43)",1
"gcd(461952, 116298)",18
"gcd(24826148, 45296490)",526
"gcd(0, 0)",0
"gcd(12, 0)",12
"gcd(0, 9)",9
"lcm(15, 20)",60
"lcm(10, 5)",10
"lcm(5, 7)",35
"lcm(1, 0)",0
"lcm(2, 0)",0
"lcm(0, 0)",0
"lcm(2, -3)",6
"lcm(-2, -2)",2
"gcd(-24, 18)",6
"gcd(-30, -9)",3
"gcd(25, -5)",5

0 comments on commit 49dd638

Please sign in to comment.