💾 Archived View for vigrey.com › blog › defining-subtraction-building-simple-computer captured on 2023-07-22 at 16:33:56. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-01-29)
-=-=-=-=-=-=-
In this post, I am going to describe how subtraction works in a very basic sense. I'm going to assume you have already read the post defining how addition works.
Defining "Addition" - Building a Simple Computer
The reason I am doing these posts describing addition, subtraction, multiplication, and division is because of a project I am working on, a simple unary based computer, which I will talk about in a later date.
Just like with addition, subtraction will start with 2 values, X and Y. The X value this time around is called the minuend, the Y value is called the subtrahend, and the answer to the subtraction problem is called the difference. You'll recognize the setup as X - Y.
In order to subtract Y from X, first check to see if X or Y is zero. If neither are zero, then decrement both X and Y. Repeat this until Y or X is zero. When X or Y reach zero, then the value in X will be the non-negative answer and Y will be the debt, which is how far below zero the answer actually is. You would normally see this in math class as a negative answer, but we are working with only non-negative integers, so this is how we'll handle it.
Describing this in terms of a person having a collection of rocks, we'll imagine this person wants to subtract a specific amount of rocks from their collection of rocks. To keep track of how many rocks need to be removed, we'll use a second collection of rocks. The person would see if either collection is empty. If neither collection is empty, the person would remove a rock from both collections. When one of the collections is empty, then the person will have ended up subtracting the amount from the second collection from the first collection.
This can be described in the following pseudo code function:
Define SUB (X, Y): If X does NOT equal 0 and Y does NOT equal 0: DEC Y DEC X SUB (X, Y)
So let's go through this function to figure out what 3 - 2.
X = 3 Y = 2 SUB (X, Y) Are X and Y both NOT 0? [Yes] DEC Y [Y now equals 1] DEC X [X now equals 2] SUB (X, Y) Are X and Y both NOT 0? [Yes] DEC Y [Y now equals 0] DEC X [X now equals 1] SUB (X, Y) Are X and Y both NOT 0? [No] ----------------------------------- | 3 - 2 equals 1 with 0 left over | -----------------------------------
Just as with Addition, you'll probably notice that because this function loops, we are technically doing 3 different but equivalent subtraction problems, 3 - 2, 2 - 1, and 1 - 0.
The only things we need in order to define subtraction are the ability to decrement, specify a value to decrement, and check if a value is 0.