Method 1
gcdList[x_, y_] :=
FixedPointList[
# /. {a_, b_} /; b != 0 :> {b, Mod[a, b]} &, {x, y}]
gcdList[25,45]
{{25, 45}, {45, 25}, {25, 20}, {20, 5}, {5, 0}, {5, 0}}
Another solution
gcd[a_, b_] :=
Module[{x, y},
{x, y} = {a, b};
While[y != 0,
{x, y} = {y, Mod[x, y]};
];
x
]
gcd[15,10]
5
Method 2
gcdList2[a_, b_] :=
Module[{x, y, res = {}},
{x, y} = {a, b};
While[y != 0,
AppendTo[res, {x, y}];
{x, y} = {y, Mod[x, y]}
];
AppendTo[res, {x, 0}]
]
gcdList2[56, 21]
{{56, 21}, {21, 14}, {14, 7}, {7, 0}}
Method 3
With the help of Sow
and Reap
gcdList3[a_, b_] :=
Module[{x, y, res},
{x, y} = {a, b};
res =
Reap[
While[y != 0,
Sow[{x, y}];
{x, y} = {y, Mod[x, y]}
]];
AppendTo[res[[2, 1]], {x, 0}]
]
gcdlist3[120, 75]
{{120, 75}, {75, 45}, {45, 30}, {30, 15}, {15, 0}}
NestWhile
. It will allow you to apply a function recursively until a user-specified condition is met. Here is its documentation page. Also, unless you are doing this for practice, Mathematica already has a built-in function to calculate the greatest common divisor, calledGCD
(docs here). You could use that one as a step towards solving your problem. $\endgroup$GreatestCommonDivisor[list_] := Module[{r1, r2, r3, r, a, b, n, k, p}, a = list[[1]]; b = list[[2]]; r[1] = a - Floor[a/b]* b; r[2] = b - Floor[b/r1] r1; r[3] = r1 - Floor[r1/r2] r2; r[n_] := r[n - 2] - Floor[r[n - 2]/r[n - 1]]*r[n - 1]; Return[NestWhile[r, 4, # != 0 &, 1, \[Infinity], -1]] ]
$\endgroup$