If you can use Java 8 (and really want to), you can use lambda expressions to solve this problem:
private static int gcd(int x, int y) { return (y == 0) ? x : gcd(y, x % y); } public static int gcd(int... numbers) { return Arrays.stream(numbers).reduce(0, (x, y) -> gcd(x, y)); } public static int lcm(int... numbers) { return Arrays.stream(numbers).reduce(1, (x, y) -> x * (y / gcd(x, y))); }
I was guided by Jeffrey Hantin answer , but
- computed gcd functionally
- used the varargs syntax for a simpler API (I was not sure if the overload would work correctly, but it works on my machine)
- converted gcd
numbers -Array to a functional syntax that is more compact and IMO easier to read (at least if you are used to functional programming)
This approach is probably a bit slower due to extra function calls, but it probably doesn't matter at all for most use cases.
Qw3ry Nov 10 '16 at 15:27 2016-11-10 15:27
source share