1 | initial version |
It seems that you try to use the following idea: $\gcd(f,g) = f$ if $g=0$ and otherwise it equals $\gcd(g, f \mbox{ mod } g)$. So while $g \neq 0$ you should set $(f, g) := (g, f \mbox{ mod } g)$, and at the end return $f$. To express this without assignment of a tuple (even though that is possible in SageMath/Python) you can use a temporary variable, say $r$: first put $r:=g$ and then $g:=f \mbox{ mod } g$ and then $f:=r$. In code it becomes:
def mygcd(f,g):
while g != 0:
r = g
g = f % g
f = r
return f/f.lc()
You almost had this, just somehow not using the temporary variable correctly. I also changed the last line to return a monic polynomial (this is a convention, e.g. followed by SageMath's own gcd
).
The function works when passed elements of a polynomial ring such as R.<x> = PolynomialRing(QQ)
.