10

I am seeking for the easiest solution to get the greatest common divisor of multiple values. Something like:

x=gcd_array(30,40,35) % Should return 5
x=gcd_array(30,40) % Should return 10

How would you solve this?

Many thanks!

Caniko
  • 867
  • 2
  • 11
  • 28
  • possible duplicate of [Euclidian greatest common divisor for more then two numbers](http://stackoverflow.com/questions/1231733/euclidian-greatest-common-divisor-for-more-then-two-numbers) – starblue Jun 19 '12 at 11:42

2 Answers2

22
gcd(a,b,c) = gcd(a,gcd(b,c))

Which means you can use recursion.

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.73.3&rep=rep1&type=pdf&ei=90jgT9KPAtLS4QSNlOGdDQ&usg=AFQjCNGH_GewFofxWPfX2BDN6T5NF9PxAA

flec
  • 2,891
  • 1
  • 22
  • 30
0
 `% GCD OF list of Nos using Eucledian Alogorithm 
  function GCD= GCD(n);
  x=1;
  p=n;
  while(size(n,2))>=2
  p= n(:,size(n,2)-1:size(n,2));
  n=n(1,1:size(n,2)-2);
  x=1;
  while(x~=0)
  x= max(p)-min(p);
  p = [x,min(p)];
  end    
  n=[n,max(p)];
  p= [];
  end
  '
Shashank
  • 9
  • 1
  • 1
    Care to explain your solution? – everton Nov 12 '14 at 20:30
  • 1
    Function GCD takes list list of numbers as its argument Now , using gcd(a1,a2,a3)= gcd(a1,gcd(a2,a3). Store the last two numbers in different matrix P To calculate the GCD of P , use the algorithm gcd of a1 & a2= a1-a2 (a1-a2)-a2 and so on till u get 0 or 1 store the GCD value again in n so that now you have n = (a1,a2,a3............a(n-2),gcd(an-1,an)) – Shashank Nov 13 '14 at 04:18