diff --git a/app/src/main/java/ch/nuth/zhaw/exbox/LCMServer.java b/app/src/main/java/ch/nuth/zhaw/exbox/LCMServer.java new file mode 100644 index 0000000..a7a28e4 --- /dev/null +++ b/app/src/main/java/ch/nuth/zhaw/exbox/LCMServer.java @@ -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; + } +}