Separated from exgcd for more logical code organization