6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby] (巨大な整数でも) 冪剰余を求める

6
Last updated at Posted at 2019-03-08

概要

冪剰余 とは冪乗の剰余のことです。

例えば $ 4^{13} \bmod 497 $ を Ruby で計算すると

4 ** 13 % 497
# => 445

となります。

では $ 4^{1234567890} \bmod 497 $ は?

4 ** 1_234_567_890
# warning: in a**b, b may be too big
# => Infinity

4 ** 1_234_567_890 % 497
# warning: in a**b, b may be too big
# => NaN

$ 4^{1234567890} $ が巨大な整数となってしまうため計算できません :sob:

こんなときでもあら不思議、Integer#pow を使うと……

4.pow(1_234_567_890)
# warning: in a**b, b may be too big
# => Infinity

4.pow(1_234_567_890, 497)
# => 190

求めることができるのだ :tada:

なお Integer#pow で第 2 引数を与えることで冪剰余が計算できるようになったのは Ruby 2.5.0 からでした。

参考

6
4
1

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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?