Please explain the algorithm, and what each variable is used for. Single letter variable names tell us nothing about what they are for.

Have you tried to find out where the values in the variables start going wrong? If you print the relevant variables after each line, then you will be able to follow through the program working out what the values should be, and checking after each line what the values are. Then you will be able to spot the differences and then you can work out why it is going wrong.