Official
B - 9x9 Sum Editorial by en_translator
This problem is an exercise of for
statements. If you could not solve this problem, learn the features and usages of for
statements.
We will explain the solution. There are multiple approaches; a simple one would be to scan the grid, and add the current number to the answer if it is not \(X\). That is, it is sufficient to implement the following algorithm:
- Let \(\mathrm{ans}\) be the variable to store the answer. Initially, \(\mathrm{ans}\) is \(0\).
- For each \(i = 1, 2, \dots, 9\) in order, do the following.
- For each \(j = 1, 2, \dots, 9\) in order, do the following.
- Suppose that you are inspecting the cell in the \(i\)-th row from the top and \(j\)-th column from the left. The integer written on the cell is \(i \times j\). If this value is not \(X\), add \(i \times j\) to \(\mathrm{ans}\).
- For each \(j = 1, 2, \dots, 9\) in order, do the following.
- The answer is the value \(\mathrm{ans}\) after all the process is done.
The complexity is \(\mathrm{O}(N^2)\) where the size of grid is \(N\). This time, \(N = 9\), so it runs fast enough.
- Sample code (C++)
#include <iostream>
using namespace std;
int main() {
int X;
cin >> X;
int ans = 0;
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
if (i * j != X) ans += i * j;
}
}
cout << ans << endl;
}
posted:
last update: