How to calculate GCD vectors in GNU Octave / Matlab

gcd (A1, A2, ...)calculates GCD elements A1(1), A2(1), .... Being elements stored in a vector A, how to calculate gcd (A)?
(I mean gcd (4, 2, 8) = 2, gcd ([4, 2, 8]will cause an error in GNU Octave 4.0.0).

+4
source share
3 answers

With cell array expansion

Here is one liner valid only in octave (thanks to nirvana-msu for specifying matlab restrictions):

A = [10 25 15];
gcd(num2cell(A){:})
# ans =  5

This is using the cell array extension, which is a little hidden there :

'{'} ,

A{:} A(1), A(2), A(3), , , gcd(A{:}) gcd(A(1), A(2), A(3))


A = 3:259;
tic; gcd(num2cell(A){:}); toc

Elapsed time is 0.000228882 seconds.

gcd_vect @nirvana_msu,

tic; gcd_vect(A); toc

Elapsed time is 0.0184669 seconds.

, ( , ). 256 .

tic; gcd_vect(1:257); toc

<... snipped bunch of errors as ...>
error: evaluating argument list element number 2
error: called from
gcd_vect at line 8 column 13

,

( ) :

A = 127:100000;
tic; gcd(num2cell(A){:}); toc
Elapsed time is 0.0537438 seconds.

( )

Matlab ( , ).

, ,

function g = gcd_array(A)
  N = numel(A);

  if (mod(N, 2) == 0)
    % even number of elements
    % separate in two parts of equal length
    idx_cut = N / 2;
    part1 = A(1:idx_cut);
    part2 = A(idx_cut+1:end);
    % use standard gcd to compute gcd of pairs
    g = gcd(part1(:), part2(:));
    if ~ isscalar(g)
       % the result was an array, compute its gcd
       g = gcd_array(g);
    endif
  else
    % odd number of elements
    % separate in one scalar and an array with even number of elements
    g = gcd(A(1), gcd_array(A(2:end)));
  endif
endfunction

:

A = 127:100000;
tic; gcd_array(A); toc
Elapsed time is 0.0184278 seconds.

, , .

+1

- , , ,

function g = gcd_array(vals)
if length(vals) == 1
    g = vals;
else
    g = gcd(vals(1), gcd_array(vals(2:end)));
endif
+1

, Octave Matlab gcd . - , gcd(a,b,c) = gcd(a,gcd(b,c)). : , , Matlab, Octave:

function divisor = gcd_vect(a, varargin)
    if ~isempty(varargin)
        a = [a, varargin{:}];
    elseif length(a) == 1
        divisor = a;
        return;
    end
    divisor = gcd(a(1), gcd_vect(a(2:end)));
end
0

All Articles