Search code examples
arraysmatlabgreatest-common-divisor

How to calculate GCD in MATLAB (variable array)?


I have problem in calculating GCD. Usually GCD in MATLAB uses two variables (ex: a=19, b=88 and gcd(a,b)). But I have one variable array K = [1 1 1 1 2 1 3 2], and for this K, I want to calculate GCD.
How to calculate greatest common divisor of K ?


Solution

  • Because gcd(gcd(a,b),c) is the same as gcd(a,b,c) you can iterate through K and get the gcd of the array.

    g = K(1)
    for i=2:numel(K)
        g = gcd(g,K(i))
    end
    fprintf('The gcd is %i\n', g)