How to calculate the difference between two numbers in a sequence that wraps around?

367 Views Asked by At

I am dealing with a problem that has a solution in this simplified problem's solution.

Assume there is a sequence of numbers 0-99. There is a wrap-around such 99+1 = 0 and 0-1=99. The position 100 and 0 overlap. The diagram below will help to visualize this. The number 10 is shown so the scenarios mentioned below are easier to visualize.

enter image description here

We want to calculate the difference between two numbers to find the shortest way to get from A to B.

Scenario 1;
B = 75 (end)
A = 50 (start)
Shortest path is clockwise B-A=25, starting at A=50

Scenario 2;
B=50 (end)
A=75 (start)
Shortest path is anti-clockwise B-A=-25, starting at A=75

So far so good, now for the trouble.

Scenario 3;
B=10 (end)
A=75 (start)
Shortest path would be clockwise 10+25=35; starting at A=75
But what is the formula?

Scenario 4;
B=75 (end)
A=10 (start)
Shortest path would be anti-clockwise -10-25=-35; starting at A=10
But what is the formula?

When going from A to B requires to go over the wrap around point, the simple formula A-B or B-A does not work anymore. So what is the formula that will work with all the scenarios to give the correct sign and the magnitude to move? +ve sign is clockwise while -ve sign is anti-clockwise.

EDIT:

Since I have to implement a hardware design, it is important to be able to not use division or modulus. Only multiplication, addition and subtraction can be used.