Java Program for GCD of more than two (or array) numbers
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers.
gcd(a, b, c) = gcd(a, gcd(b, c))
= gcd(gcd(a, b), c)
= gcd(gcd(a, c), b)
Java
public class GCD {
static int gcd( int a, int b)
{
if (a == 0 )
return b;
return gcd(b % a, a);
}
static int findGCD( int arr[], int n)
{
int result = arr[ 0 ];
for ( int i = 1 ; i < n; i++)
result = gcd(arr[i], result);
return result;
}
public static void main(String[] args)
{
int arr[] = { 2 , 4 , 6 , 8 , 16 };
int n = arr.length;
System.out.println(findGCD(arr, n));
}
}
|
Time complexity: O(n)
Space complexity: O(1)
Please refer complete article on GCD of more than two (or array) numbers for more details!
Last Updated :
31 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...