Try adding a print statement in the loop that prints m,n,q each time through. You can then compare them to the expected values in the book. Note that the values used in the proof are the values at each stage; so 544=(119*4)+68 after stage1 and (32*17)+0 at the final stage. 32 being the remainder (m MOD n) from the previous stage (51 MOD 17)=32 .