Write a program which multiplies an N digit number M by a 1 digit number d, where N could be large, e.g. 1000. The input will be given as follows. First, the user gives d, then N and then the digits of M, starting from the least significant to the most significant. The program must print out the digits of the product one at a time, from the least significant to the most significant.
Hint: Mimic the process of manual multiplication. Keep track of the current carry in a variable and update it as you go along.
Here's result, you can see result of multiplication by looking at digits in console from bottom to top (least significant will be printed as "Next result digit:" first)
#include <iostream>
int main() {
int d, N;
std::cout << "Enter multiplier d value: ";
std::cin >> d;
std::cout << "Enter number of digits N: ";
std::cin >> N;
int curDigit, carry = 0;
std::cout << "Beginning multiplication...\n";
while (N-- > 0) {
std::cout << "Enter next digit of M: ";
std::cin >> curDigit;
int prod = curDigit * d + carry;
carry = prod / 10;
std::cout << "Next result digit: " << prod % 10 << std::endl;
}
if (carry > 0) {
std::cout << "Last result digit: " << carry << std::endl;
}
return 0;
}
Comments
Leave a comment