0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

yukicoder No.2781 A%B問題 解説

Posted at

問題文

解説

普通に$A$%$B$を出力するだけ...とは言えない。
一般に%は$A$が負であるかつ$A\bmod{B}\neq 0$のとき答えが正しく作動しない。
よって、次のような場合分けをする。
$A\bmod{B}=A$%$B(A\geq0$または$A\bmod{B}=0)$
$A\bmod{B}=A$%$B+B(A<0$&$B\geq 0)$
$A\bmod{B}=A$%$B-B(A<0$&$B< 0)$
この通りに場合分けして実装すれば解ける。

C++での解答例

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

int main() {
  int a, b;
  cin >> a >> b;
  if(a >= 0 || a % b == 0) cout << a % b << endl;
  else if(b >= 0) cout << a % b + b << endl;
  else cout << a % b - b << endl;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?