greatest-common-divisor

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

独自空忆成欢 提交于 2019-11-26 13:48:30
问题 what is the fastest way to compute the greatest common divisor of n numbers? 回答1: You should use Lehmer's GCD algorithm. 回答2: 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 gcd(numbers);

Euclidean algorithm (GCD) with multiple numbers?

冷暖自知 提交于 2019-11-26 09:58:46
问题 So I\'m writing a program in Python to get the GCD of any amount of numbers. def GCD(numbers): if numbers[-1] == 0: return numbers[0] # i\'m stuck here, this is wrong for i in range(len(numbers)-1): print GCD([numbers[i+1], numbers[i] % numbers[i+1]]) print GCD(30, 40, 36) The function takes a list of numbers. This should print 2. However, I don\'t understand how to use the the algorithm recursively so it can handle multiple numbers. Can someone explain? updated, still not working: def GCD

How to find GCD, LCM on a set of numbers

狂风中的少年 提交于 2019-11-26 03:49:29
问题 What would be the easiest way to calculate Greatest Common Divisor and Least Common Multiple on a set of numbers? What math functions can be used to find this information? 回答1: 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