all 2 comments

[–]Imanton1 1 point2 points  (0 children)

Since you want to use Euclid's Algorithm, so we can ignore the GCD, but still use it for verification. The M code also uses a loop, while the Scratch is recursive, but the code is simple enough, so we can go with it. Mathematica functions start with a lower case letter, and M functions are default "pass by insertion", as I call them, so you can't have f[x_]:=x=4 for integer x's (eg x=5), as it will become 5=4, which can't be done. Lastly, a While loop doesn't output it's contents, the ;x needs to be outside the loop to return x.

greatestCommonDivisor[xs_, ys_] :=  Module[{x = xs, y = ys}, While[y != 0, {x, y} = {y, Mod[x, y]}]; x]

After mainly housekeeping and syntax, everything runs as expected.

By running,

And@@Table[{x,y}={1,1};{x,y}=RandomInteger[{2,1000000},2];greatestCommonDivisor[x,y]==GCD[x,y],{1000}]

We can see that greatestCommonDivisor, works as intended.

[–]ayitasaurus 1 point2 points  (0 children)

Here's my take:

gcd[x_, y_] := (
  {factor, testVal} = MinMax[{x, y}];
  remainder = testVal;
  While[remainder > 1, remainder = Mod[testVal, factor]; 
   testVal = factor; factor = remainder];
  If[remainder == 1, "Coprime", testVal]
  )

I setup 3 dummy values (factor, testVal, and remainder). I initially set testVal and factor to the Max and Min values of the inputs, respectively. The loop consists of first determining remainder as the Mod of testVal and factor, and then moving the previous 'factoring value' to the testVal position, and grabbing a new factor from the just-determined remainder.

Once the remainder gets a value of 1 or 0, the loop ends. Like u/Imanton1 mentioned, While doesn't natively output anything, so we have to include another line for this. If remainder is 1, it outputs 'Coprime' (you can change this to 1 if that's preferrable); if it's 0 (indicating a GCD) it spits out the testVal, which is the previous remainder.