Shift-and-add is a mathematical trick where we use the process of adding and shifting to multiply two numbers together. Imagine you have two numbers, let's say 3 and 4, and you want to multiply them together. Instead of doing the multiplication the usual way (3 times 4 equals 12), we will use the shift-and-add technique.
To do this, we first write down the two numbers in binary form (which means using only 0s and 1s):
3 in binary is 011
4 in binary is 100
Then, we start with the first digit of the second number (which is 1 in this case) and we shift it to the left by one place. This means we add a zero to the end of the number:
1 becomes 10
Next, we look at the second digit of the second number (which is 0) and do the same thing:
0 becomes 00
We continue this process until we have gone through all the digits in the second number. Each time we shift a digit to the left, we add a zero to the end of the number.
Now, we look at the binary forms of the second number, which are:
100
010
001
For each of these binary forms, we check if the rightmost digit is a 1. If it is, we add the first number (which is 3 in this case) to a running total.
Let's go through an example:
- Is the rightmost digit of 100 a 1? Yes, it is.
- So we add 3 to our running total (which starts at 0) to get 3.
- Is the rightmost digit of 010 a 1? No, it's a 0.
- Is the rightmost digit of 001 a 1? Yes, it is.
- So we add 3 to our running total (which is now 3) to get 6.
The final result of using shift-and-add to multiply 3 and 4 is 6.
This technique might seem a bit strange, but it can be very useful for multiplication when we don't have access to a calculator or we need to do lots of calculations quickly.