Add LCMServer
class
This commit is contained in:
parent
1cf8747072
commit
d13598d9c0
1 changed files with 40 additions and 0 deletions
40
app/src/main/java/ch/nuth/zhaw/exbox/LCMServer.java
Normal file
40
app/src/main/java/ch/nuth/zhaw/exbox/LCMServer.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue