Created
December 23, 2015 12:17
-
-
Save pedrotoliveira/e648011dc041f58cdcc0 to your computer and use it in GitHub Desktop.
Euclidean Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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