Code covered by the BSD License  

Highlights from
vecgcd

Be the first to rate this file! 6 Downloads (last 30 days) File Size: 1.44 KB File ID: #30216

vecgcd

by Steven Gregory

 

28 Jan 2011

Computes the GCD of the elements of the integer vector V.

| Watch this File

File Information
Description

G = VECGCD(V) is the greatest common divisor of the elements of the integer
vector V. V must be a row or a column vector of integers.We define gcd([]) = 1 and gcd([0 0 ... 0]) = 0.

I believe that this routine is faster than recursively computing GCDs and the algorithm is simple enough to be used for pencil and paper calculations.

MATLAB release MATLAB 7.2 (R2006a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (3)
29 Sep 2011 Peter Cotton

typo on line 47?

06 Feb 2012 Alex

I took a look and made some quick modifications to speed up the loop.

current_gcd = 0;
for i = 1: length(v)
loop_gcd = mod(v(i), current_gcd);
if(loop_gcd > 0)
  currernt_gcd = loop_gcd;
end
end

This reduces your computation time by about 1/3 for small vectors. I imagine this will increase with larger vectors, because you do not run into issues where the v vector is increasing in size as the while loop continues. Also, as the above commenter noted, you have a line that should be commented out (e x = g).

Also, this adjustment means that it doesn't matter if it is a row or column vector.

06 Feb 2012 Alex

I noted a mistake in my above code. the following line should go before the other code.

v = abs(sort(v, 'descend'));

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
gcd Steven Gregory 28 Jan 2011 15:52:30
number theory Steven Gregory 28 Jan 2011 15:52:30

Contact us at files@mathworks.com