Add LCMServer class

This commit is contained in:
Manuel Thalmann 2022-09-27 12:56:11 +02:00
parent 1cf8747072
commit d13598d9c0

View file

@ -0,0 +1,40 @@
package ch.nuth.zhaw.exbox;
import java.util.Formatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LCMServer implements CommandExecutor {
Formatter formatter = new Formatter();
Pattern pattern = Pattern.compile("^([0-9]+),?\\s*([0-9]+)$");
@Override
public String execute(String command) throws Exception {
Matcher matcher = pattern.matcher(command);
if (matcher.find()) {
int x = Integer.parseInt(matcher.group(1));
int y = Integer.parseInt(matcher.group(2));
int result = leastCommonMultiple(x, y);
return "Das Resultat ist %d\n".formatted(result);
}
else {
throw new Exception("Der angegebene Befehl \"%s\" ist ungültig!\n".formatted(command));
}
}
public int leastCommonMultiple(int x, int y) {
return Math.abs(x * y) / greatestCommonDivisor(x, y);
}
public int greatestCommonDivisor(int x, int y) {
while (y != 0) {
x %= y;
x ^= y;
y ^=x;
x ^= y;
}
return x;
}
}