公式

F - S = 1 解説 by en_translator


An important fact is that the area of a triangle whose vertices are \((0, 0), (X, Y)\) and \((A, B)\) is \(\frac{\vert AY - BX \vert}{2}\). Thus we can consider that, given integers \(X\) and \(Y\), this problem asks to find an integer pair \((A, B)\) such that

\[\vert AY - BX \vert = 2.\]

We explain how to solve this problem. Here, we let \(g = \gcd(X, Y)\). (Note: \(\gcd(a, b)\) is defined as the greatest common divisor of \(\vert a \vert\) and \(\vert b \vert\).)
If \(g\) is \(3\) or greater, then the answer does not exist because \(AY - BX\) is always a multiple of \(g\).
If \(g = 1, 2\), then one can always obtain a solution using an algorithm called extended Euclidean algorithm. The extended Euclidean algorithm is an algorithm that, given an integer pair \((a, b)\) as input, finds an integer pair \((x, y)\) such that \(ax + by = \pm \mathrm{gcd}(a, b)\) in \(\mathrm{O}(\log \min(|a|, |b|))\) time. (Here, the integer pair \(x, y\) is guaranteed to be integers satisfying \(\max(|x|, |y|) \leq \max(|a|, |b|)\).)

// Sample implementation of extended Euclidean algorithm
pair<long long, long long> extgcd(long long a, long long b) {
  if (b == 0) return make_pair(1, 0);
  long long x, y;
  tie(y, x) = extgcd(b, a % b);
  y -= a / b * x;
  return make_pair(x, y);
}

By feeding \((Y, -X)\) as the input of extended Euclidean algorithm, one can obtain a pair \((c, d)\) such that

\[cY - dX = \pm g\]

and \(\vert c \vert, \vert d \vert \leq 10^{17}\) as the return value. What we originally wanted is a pair \((A, B)\) such that \(AY - BX =\pm 2\), which can be obtained by multiplying \(c\) and \(d\) by \(\frac{2}{g}\). This \((A, B)\) safely satisfies \(\vert A \vert, \vert B \vert \leq 10^{18}\).

Hence, the problem has been solved. The computational complexity is about \(\mathrm{O}(\log \min (X, Y))\), which is fast enough.

投稿日時:
最終更新: