How to get GCD and LCM of a range of numbers efficiently?
As mentioned by Chris J this SO question provides the algorithm. Here is a python version of the answer that uses the reduce
built-in and the fractions
module that has been around since version 2.6.
import fractions
def gcd(*values):
return reduce(fractions.gcd, values)
How to find GCD, LCM on a set of numbers
I've used Euclid's algorithm to find the greatest common divisor of two numbers; it can be iterated to obtain the GCD of a larger set of numbers.
private static long gcd(long a, long b)
{
while (b > 0)
{
long temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
private static long gcd(long[] input)
{
long result = input[0];
for(int i = 1; i < input.length; i++) result = gcd(result, input[i]);
return result;
}
Least common multiple is a little trickier, but probably the best approach is reduction by the GCD, which can be similarly iterated:
private static long lcm(long a, long b)
{
return a * (b / gcd(a, b));
}
private static long lcm(long[] input)
{
long result = input[0];
for(int i = 1; i < input.length; i++) result = lcm(result, input[i]);
return result;
}
GCD and LCM relation
The analogous formulas to
LCM(a, b) = (a x b) / GCD(a,b) or GCD(a,b) = (a x b) / LCM(a, b)
with three variables are simply not valid, as your example with (3, 12, 10) shows readily.
The product of these three numbers is 360. The GCD is 1. The LCM is 60.
Related Topics
403 Forbidden When I Try to Post to My Spring API
Spring Boot Unsupported Media Type With @Requestbody
Enter Array Without Knowing Its Size
I Want to Detect the End of Scroll Event
How to Avoid Nullpointerexception With an Empty Cell Using Poi
Convert String With Dot or Comma to Float Number
How to Query Multiple Hash Keys in Dynamodb
How to Solve Liquibase Checksum Validation Fail After Liquibase Upgrade
Java Floating Point Number in Comma Instead of Dot
Is There a Java Setting for Disabling Certificate Validation
Java Classes to Generate the Given Json String
Write to Text File from Multiple Threads
How to Process a Multipart Request Consisting of a File and a Json Object in Spring Restful Service
Convert Localdatetime to Localdatetime in Utc
Java.Lang.Noclassdeffounderror: Lorg/Apache/Logging/Log4J/Logger; But the Artifact Exists
Maven Builds Are Working, But Junit Is Throwing a Nosuchmethoderror