1
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?

More than 3 years have passed since last update.

mod p での逆元を線形時間で列挙するやつ

1
Last updated at Posted at 2022-12-16

無限に同じ内容の記事があると思います


二項係数の前計算などでよく使う, $1, 2, \cdots, n$ の $\mod p$ での逆元を前計算するやつ, ありますよね

$a ^ {-1} \equiv -(p \% a) ^ {-1} \times (p // a)\pmod p$

のように計算できるので, $a$ の小さいほうから順に計算しながらテーブルを埋めていくことで, 全体で $\Theta(n)$ で計算できます

($//$ は切り捨て除算, $\%$ は割った余りを指しています)

ところで何でこんなキモイ式なんでしょうか ぱっと見わからん気がします (僕だけですか?)

最近ライブラリ整備をしていてこれを書かされることが多くなったので, ちょっと整理します


$p = (p // a)\times a + (p \% a)$

と書けるのはわかると思います

$\text{mod}$ を取って

$0 \equiv (p // a)\times a + (p \% a) \pmod p$

いい感じに移項したら

$a ^ {-1} \equiv -(p \% a) ^ {-1} \times (p // a)\pmod p$

になりました おしまい


ところでこれは $a \le 1$ のときに死にますね (一敗)

1
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
1
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?