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*)
  ](*End Module*)
  • 5
    $\begingroup$ Your loop never terminates because the variable r is never changed within the loop. You need to redeine r within the loop. $\endgroup$
    – bill s
    Commented Oct 2, 2017 at 18:05
  • $\begingroup$ Related: mathematica.stackexchange.com/questions/138160 $\endgroup$
    – Coolwater
    Commented Oct 2, 2017 at 21:24

1 Answer 1


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 *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.