what is the fastest way to find the gcd of n numbers?

Without recursion: int result = numbers[0]; for(int i = 1; i < numbers.length; i++){ result = gcd(result, numbers[i]); } return result; For very large arrays, it might be faster to use the fork-join pattern, where you split your array and calculate gcds in parallel. Here is some pseudocode: int calculateGCD(int[] numbers){ if(numbers.length <= 2){ return … Read more

Euclidean algorithm (GCD) with multiple numbers?

Since GCD is associative, GCD(a,b,c,d) is the same as GCD(GCD(GCD(a,b),c),d). In this case, Python’s reduce function would be a good candidate for reducing the cases for which len(numbers) > 2 to a simple 2-number comparison. The code would look something like this: if len(numbers) > 2: return reduce(lambda x,y: GCD([x,y]), numbers) Reduce applies the given … Read more