Official

D - Sum of Geometric Series Editorial by en_translator


One can actually evaluate \(X\) and check if \(X \leq 10^9\).

However, note that \(X\) may not be representable within the range of a 64-bit integer type, such as long long in C++.

To circumvent this issue, one can use an arbitrary-precision integer type (known as BigInt), or successively compute \(N^0, N^1, \ldots, N^M\) and abort once it exceeds \(10^9\).

Sample code (Python)

N, M = map(int, input().split())
X = sum(N ** i for i in range(M + 1))
print(X if X <= 10 ** 9 else "inf")

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main() {
	ll n, m;
	cin >> n >> m;
	ll cur = 1, sum = 0;
	for (int i = 0; i <= m; i++) {
		sum += cur;
		if (sum > 1'000'000'000) {
			cout << "inf\n";
			return 0;
		}
		cur *= n;
	}
	cout << sum << '\n';
}

posted:
last update: