Multiply two numbers whose product does not fit in an int.
What to build
A program that chooses a type large enough for its result.
Requirements
- Read two whole numbers.
- Print
product P. - Print
last digit D. - Print
fits in intif the product is at most 2147483647, otherwisetoo big for int.
Input
One line with two whole numbers.
Output
Three lines.
Constraints
Each number is from 0 to 2000000000.
Example
Input:
3 4
Output:
product 12
last digit 2
fits in int
Why it works
Multiplying two ints overflows before the result is ever stored, so the values themselves must already be long long.
Examples
Example 1 · Input
3 4
Expected output
product 12 last digit 2 fits in int
Example 2 · Input
100000 100000
Expected output
product 10000000000 last digit 0 too big for int
Hints
Hint 1
Read both numbers into long long variables, with %lld.
Hint 2
The last digit is the value % 10.
Hint 3
Print long long values with %lld.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
long long a, b;
scanf("%lld %lld", &a, &b);
long long product = a * b;
printf("product %lld\n", product);
printf("last digit %lld\n", product % 10);
if (product <= 2147483647LL) {
printf("fits in int\n");
} else {
printf("too big for int\n");
}
return 0;
}