In C++, the largest int value is 2147483647. So, an integer larger than this cannot be stored and processed as an integer. Similarly, if the sum or product of two positive integers is greater than 2147483647, the result will be incorrect.
One way to store and manipulate large integers is to store each individual digit of the number in an array.
Write a program that inputs two positive integers of, at most, 50 digits (they can be of less than 50 digits) and can perform sum and multiplication of the input numbers.
If the sum or multiplication of the numbers has more than 50 digits, output the appropriate message.
Your program will have following functions:
1. A function to read and store a number into an array
2. A function to Multiply the two large input numbers and output the result.
You must perform the grade school multiplication. You can’t simply convert number to integer and multiply.
Please help with multiplication.
Is there is any way to do this with arrays in C++ without using some more advanced functions.
Since you know the maximum quantity of digits is 50, you can use an array:
const unsigned int MAXIMUM_DIGITS = 50U;
char number_digits[MAXIMUM_DIGITS];
By keeping as characters, you won't have to perform any division to extract digits from a number.
To convert a character to an internal number, you can use:
unsigned int number = number_digit[i] - '0';
Or search an array:
char decimal_digits[] = "0123456789";
char * p = strchr(decimal_digits, number_digit[i]);
unsigned int number = p - &decimal_digits[0];
Multiplication of the digits is left as an exercise for the OP.
Edit 1: Multiplication
An algorithm for multiplication is:
unsigned int carry = 0U;
// Multiply the two digits
// The two digits should be unsigned int
unsigned int product = digit_1 * digit_2;
// Add in the carry from a previous multiply
product += carry;
// Calculate carry (overflow) from the product.
carry = product / 10;
// Trim the product to one digit.
product = product % 10;