An ancient method for multiplying two integers works by repeated multiplication and division by 2. Lets say you have two numbers (X and Y). Multiply X by 2 and divide (integer division) Y by 2. Repeat the process until Y becomes zero and you cant divide any further. The result of multiplying X by Y is the total of all the values of X whenever Y was odd.
Here is an example of multiplying 30 by 18:
X | Y |
30 | 18 |
60 | 9 |
120 | 4 |
240 | 2 |
480 | 1 |
0 |
Result = 60 + 480 = 540.
Write a C++ program that repeatedly asks the user (y/n question) for two positive integers to multiply and uses the method outlined above to calculate and display the result of multiplication. Validate the input values to make sure they are both positive. Your program should repeatedly ask the user to reenter each number until they enter a positive integer.
Reviews
There are no reviews yet.