Addition without Internal Carries
National Olympiad — Municipal round (2016 season)
Submission name: sum.cpp
Problem summary
Goshko adds two three-digit numbers but forgets carries into the tens and hundreds columns. He still writes the full sum of the hundreds digits, including any thousands digit. Print his mistaken result and the correct sum.
Input
An expression A+B with no spaces.
Output
The mistaken sum on the first line and the correct sum on the second.
Constraints
100 ≤ A, B ≤ 999.
Worked example
An independently prepared example for this explanation.
Input
128+924
Output
1042 1052
Solution analysis
- Extract the units, tens and hundreds of each input. The units result is the units-digit sum modulo 10. The tens result is the tens-digit sum modulo 10, with no incoming carry.
- The hundreds-digit sum is kept in full because there is no restriction against writing its thousands digit. Combine these pieces as 100 × hundredsSum + 10 × (tensSum % 10) + unitsSum % 10.
- For 128 + 924 the units give 8 + 4 = 12, so write 2 without carrying. The tens give 2 + 2 = 4 and the hundreds give 1 + 9 = 10, producing 1042. Ordinary addition gives 1052.
Why it works
Each of the lower two columns is computed independently and retains exactly its last digit, implementing the omitted outgoing carry. The full hundreds sum supplies the remaining leading digits. The positional-value combination is consequently Goshko’s calculation; normal A + B is the true sum.
Watch out. Do not discard the thousands digit from the hundreds sum. Parse the plus sign explicitly.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int a, b;
char plus;
cin >> a >> plus >> b;
int units = (a % 10 + b % 10) % 10;
int tens = ((a / 10) % 10 + (b / 10) % 10) % 10;
// Hundreds retain their full sum, including its possible thousands digit.
int hundreds = a / 100 + b / 100;
cout << hundreds * 100 + tens * 10 + units << '\n';
cout << a + b << '\n';
return 0;
}