In a unit-cost random access machine, the value of a register \(r_i\) can be set to the value of another register \(r_j\) plus/minus a constant \(c\in\mathbb N\) using basic \(L O O P\) commands as well as the algorithm for \(r_i:=\pm c\) and the algorithm for the NOP operation.
Although the unit-cost random access machine is not able to store negative numbers in its registers, it is not much more complicated to calculate the difference of a registers \(r_j\) and a positive constant, because negative integers can be represented by pairs of natural numbers, as shown in the definition of integers. Thus, it is possible to build a unit-cost random access machine, which is able to store negative numbers using more auxiliary registers representing integers as pairs of natural numbers and implementing an appropriate subtraction operation on these pairs.
class UCRAM(): # unit-cost random access machine with 3 registers r_i = 0 r_j = 0 r_n = 0
def LOOP_r_j_DO_increment_r_i(self):
while True:
if self.r_j > 0:
self.r_j = self.r_j - 1 # LOOP register j
self.r_i = self.r_i + 1 # DO increment register i
else:
break
def set_r_n_to_10(self):
# set r_n=0 with loop r_n do
while True:
if self.r_n > 0:
self.r_n = self.r_n - 1 # LOOP register n
self.NOP() # DO nothing
else:
break
# set register to 10 by incrementing it 10 times
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
self.r_n = self.r_n + 1
def LOOP_r_n_DO_increment_r_i(self):
while True:
if self.r_n > 0:
self.r_n = self.r_n - 1 # LOOP register n
self.r_i = self.r_i + 1 # DO decrement register j
else:
break
def NOP(self):
self.r_i = self.r_i + 1 # LOOP register i
self.r_i = self.r_i - 1 # LOOP register i
def add_ri_plus_rj_plus_constant(self):
# setting r_i:=r_j
self.LOOP_r_j_DO_increment_r_i()
# setting r_i:=r_j + 10
self.LOOP_r_n_DO_increment_r_i()
ucram.set_r_n_to_10() print(ucram.r_i, ucram.r_j, ucram.r_n)
ucram.add_ri_plus_rj_plus_constant() print(ucram.r_i, ucram.r_j, ucram.r_n)