Approach to managing decreasing set of interconnected numbers

30 Views Asked by At

We have four variables:

  • a, which represents numbers from 0-999
  • b, which represents a1000 (b = 3 represents a = 3000)
  • c, which represents b1000
  • d, which represents c100 (not 1000)

What is the easiest, most efficient or just the standard way of dealing with subtraction/addition to any of those numbers? Imagine I decrease a with 500, while it represents 0, but since b could be 1 (hence a can be 1000) I can and have to recalculate a and b.

1

There are 1 best solutions below

1
On BEST ANSWER

I will use $(a,b,c,d)$ to denote the number $a + 10^3 \cdot b + 10^6 \cdot c + 10^8 \cdot d$ (the total amount of "$a$-units"). I will assume that we have $$ 0 \leq a \leq 999 , \quad 0 \leq b \leq 999 , \quad 0 \leq c \leq 99, \quad 0 \leq d. $$ We can calculate the representation (a,b,c,d) of (a_1,b_1,c_1,d_1) + (a_2,b_2,c_2,d_2) with the process described in the pseudocode below.

initialize a = b = c = d = 0
a = a + a_1 + a_2
if a > 999
    a = a - 1000
    b = 1
b = b + b_1 + b_2
if b > 999
    b = b - 1000
    c = 1
c = c + c_1 + c_2
if c > 99
    c = c - 100
    d = 1
d = d + d_1 + d_2

Of course, all this can be implemented with a loop if we take $a,b,c,d$ as elements of an array.

We can calculate (a_1,b_1,c_1,d_1) - (a_2,b_2,c_2,d_2) similarly. The first step after initializing variables would be

if a_2 > a_1
    a_2 = a_2 + 1000
    b_2 = b_2 - 1
a = a_2 - a_1

Repeat this until the last step:

if d_2 > d_1
    [underflow error]
d = d_2 - d_1