Skip to content

Instantly share code, notes, and snippets.

@pedrotoliveira
Created December 23, 2015 12:17
Show Gist options
  • Save pedrotoliveira/e648011dc041f58cdcc0 to your computer and use it in GitHub Desktop.
Save pedrotoliveira/e648011dc041f58cdcc0 to your computer and use it in GitHub Desktop.
Euclidean Algorithm
public class EuclideanAlgorithm {
private final List<Long> numbers;
public EuclideanAlgorithm(final List<Long> numbers) {
this.numbers = Collections.unmodifiableList(numbers);
}
public long calculateGCD() {
Iterator<Long> it = numbers.iterator();
long result = it.next().longValue();
while(it.hasNext()) {
result = gcd(result, it.next().longValue());
}
return result;
}
public long calculateLCM() {
Iterator<Long> it = numbers.iterator();
long result = it.next().longValue();
while(it.hasNext()) {
result = lcm(result, it.next().longValue());
}
return result;
}
private long gcd(long n1, long n2) {
return (n2 == 0) ? n1 : gcd(n2, n1 % n2);
}
/**
* https://en.wikipedia.org/wiki/Least_common_multiple#Reduction_by_the_greatest_common_divisor
*/
private long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment