Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

what is the fastest way to compute the greatest common divisor of n numbers?

like image 599
Themasterhimself Avatar asked Feb 03 '11 11:02

Themasterhimself


People also ask

What is the easiest way to find the GCD of two numbers?

Step 1: Applying Euclid's division lemma to a and b we get two whole numbers q and r such that, a = bq+r ; 0 r < b. Step 2: If r = 0, then b is the HCF of a and b. If r ≠0, then apply Euclid's division lemma to b and r. Step 3: Continue the above process until the remainder is zero.

What are the three different algorithms used to find the GCD of two numbers?

Algorithm to find GCD using Stein's algorithm gcd(a, b) gcd(a, 0) = a and gcd(0, b) = b because everything divides 0. If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor. Multiplication with 2 can be done with bitwise shift operator. gcd(a, b) = gcd(a, b/2).

Which algorithm is used for finding GCD?

In mathematics, the Euclidean algorithm, or Euclid's algorithm, is an efficient method for computing the greatest common divisor (GCD) of two integers (numbers), the largest number that divides them both without a remainder.


1 Answers

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);         }     else {         INVOKE-IN-PARALLEL {             left = calculateGCD(extractLeftHalf(numbers));             right = calculateGCD(extractRightHalf(numbers));         }         return gcd(left,right);     } } 
like image 137
dogbane Avatar answered Sep 20 '22 09:09

dogbane