Missing Number
Missing Number
CSES
Abridged problem statement
Given all numbers from except one, find the missing number.
Solution
There are multiple ways to solve this problem. One of the simplest is to recall the identity
so we sum up all input numbers and subtract this from the sum of the first numbers.
#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
int main() {
int n;
cin >> n;
int64 sum = 0;
for (int i = 0, x; i < n - 1; ++i) {
cin >> x;
sum += x;
}
cout << int64(n) * (n + 1) / 2 - sum << '\n';
}There are two noteworthy implementation details here:
- First, we use
int64for the variablesum. This is because, for , the value of the sum is on the order of , which exceeds the limit of a regularint. As a general rule of thumb, sums of many numbers should usually be stored in wider integer types. - Secondly, while printing the answer, needed to be casted to an
int64. Again, this is to prevent overflow: otherwise, the multiplicationn * (n + 1)would be evaluated using regularintarithmetic.