1

My assignment is to calculate the GCD of two numbers n and m using the Euclidean Algorithm which basically states that if the remainder = 0 the GCD is the 2nd of the two numbers. SO my thought was to write a recursive program looking for the GCD of two numbers, if the remainder is not 0 then change n to m and m to r and then calculate the GCD of those two numbers until you get a remainder of 0. I am not strong with recursion and my program loops forever. Any help would be greatly appreciated!

MyBetterGCD[n_, m_] :=
 Module[{q, r, DebugFlag = True},
  r = Mod[n, m]; (*remainder*)
  While[r != 0,
   q = Floor[(n/m)]; (*quotient*)
   n = m;
   m = r;
   MyBetterGCD[n, m];
   ];(*End While Loop*)
  Return[m]
  ](*End Module*)
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574

1 Answers1

5

Generally speaking you are trying to use a loop AND recursion. Usually you need one of those. Also Recursive Euclidean algorithm in Mathematica addresses this algorithm.

But you probably want to completely avoid loops since you are using Mathematica. Something like this should work:

gcd[a_, 0] := a;
gcd[a_, b_] := gcd[b, Mod[a, b]];
gcd[24, 18]
(* 6 *)
BlacKow
  • 6,428
  • 18
  • 32