Can somebody please explain this code to me? I understand what it does but I don't understand how it works.
# >n 0 d
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
# >0 n d-n%d n%d n/d
Can somebody please explain this code to me? I understand what it does but I don't understand how it works.
# >n 0 d
[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]
# >0 n d-n%d n%d n/d
Here's what happens:
This line, is a comment line telling you what the memory should be like before the operation. Dividend as
n
, divisor asd
. According to the code the next 3 cells should be empty as well, but it is ignored here, assuming you have it empty by default.For easier understanding, I'll now use 25/4 as an example:
This line can be broken into parts for easier observation, but if you're just using it it's a magic loop:
This part minuses the dividend, adds it back on the next cell for preservation, and minuses the divisor. The memory now is:
This adds the removed one from the divisor, for preserving again, since we need it to loop back.
Then, it moves 2 steps rightwards to cell
005
, then006
because of a>
in between, skipping the[+[-<+>]>+>>]
since the cell is empty, then back to cell 000 because of this line:The extra movement is important because, in order for the system not to loop back again, we need to move to an empty space. moving to
006
is basically because of the extra>
, which is required for later usage.Let's skip some steps, and move forward until the divisor becomes 0.
It skips the
[>+>>]
since cell 2 is empty now, and then it moves to cell003
.Since
003
has a value, it has to run this line. adding one to the value to make it an complete loop, then shift the value back to002
with the[-<+>]
. The pointer ends at003
, so it moves to004
and to add the value by one to indicate a full cycle and thus one more to the quotient. It moves to006
and back to000
.Repeat the whole thing, then we get:
which is like the last line
as loop terminates because
000
is now empty. n is now fully shifted to the001
,002
and003
shows the loop process of the divisor when the n is fully zeroed.004
shows the total completed iteration of the divisor loop.