def extgcd(A,B): #return p,q,r such that Ap+Bq=r if A>B: q,p,r=extgcd(B,A) return p,q,r if A==0: return 0,1,B # B=cA+R then Ap+Bq=Ap+(cA+R)q=(cq+p)A+qR c=B/A R=B%A q,cqp,r=extgcd(R,A) return cqp-c*q,q,r def gcd(A,B): if B