Official

B - AtCoder Condominium Editorial by en_translator


The room number of the \(j\)-th room on the \(i\)-th floor can be regarded as a three-digit integer \(100i+j\). It is sufficient to sum them up with a double loop. Since at most \(81\) integers less than \(1000\) is summed up, the answer clearly fits in a \(32\)-bit integer.

Actually, the value can be written in a single expression. Considering summing up each of \(100i\) and \(j\), it can be found as

\[ 100(1+2+\cdots +N)\times K+(1+2+\cdots +K)\times N=\frac{NK\{100(N+1)+(K+1)\}}{2}. \]

When using this, you have to compute the numerator first before dividing it by \(2\), or the result may have an error. For example, if you calculate \(\frac{NK}{2}\) in an integer type beforehand, the result will differ from the actual value when both \(N\) and \(K\) are odd.

The following sample code is based on the first strategy.

Sample code in C++:

#include<bits/stdc++.h>

using namespace std;

int main(void) {
	int n, k;
	int s = 0;
	cin >> n >> k;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= k; j++) {
			s += (100 * i + j);
		}
	}
	cout << s << endl;
	return 0;
}

Sample code in Python:

n, k = map(int, input().split())
s = 0
for i in range(1,n+1):
    for j in range(1,k+1):
        s += (100*i)+j
print(s)

posted:
last update: