LoginSignup
2
0

More than 3 years have passed since last update.

Pythonで負の数の余りを求めるとどうなる?

Posted at

目的

余りを求める計算はよく行う
例えばリストで余りを使えば要素数をオーバーしても最初に戻って参照できる

array = ["a", "b", "c"]
index = 2

print(array[index])
#>> c

print(array[index+1])
#IndexError: list index out of range

print(array[(index+1)%3])
#>> a

ここで単純な疑問
負の数の余りを求めたらどうなるんだろう
数学としては余りは正の数になる
果たしてそうなるのか、もしくはエラーになるのか

やってみた

負の数を3で割った余りを求めてみる

print(-1%3)
#>> 2
print(-2%3)
#>> 1
print(-3%3)
#>> 0
print(-4%3)
#>> 2
print(-5%3)
#>> 1
print(-6%3)
#>> 0

全て正の数
(割られる数) = (割る数) * (商) + (余り)
を満たす余りになった
余りは割る数より小さいという法則も満たしている

まとめ

予想通り計算結果は割る数の範囲でループした
使い道はなくはなさそう

2
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
2
0