Skip to content
This repository was archived by the owner on May 22, 2026. It is now read-only.

Commit 6dd0683

Browse files
feat: fermat's little theorem
1 parent b64a9d5 commit 6dd0683

3 files changed

Lines changed: 62 additions & 0 deletions

File tree

data_structure/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,17 @@
4848
---
4949

5050
## ツリー(Tree)
51+
52+
### 普通の木
53+
54+
- 各ノードが複数の子ノードを持つことができるデータ構造。
55+
56+
#### 実装例
57+
58+
- [ ] Python
59+
- [ ] C
60+
- [x] Haskell
61+
62+
### BST(Binary Search Tree)
63+
64+
[../search/bst/](../search/bst/)に実装した。

math/README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,25 @@
1616

1717
[eratosthenes](./eratosthenes/)
1818

19+
### 実装例
20+
1921
- [] C
2022
- [] Python
2123
- [x] Haskell
2224

2325
---
26+
27+
## フェルマーの小定理
28+
29+
フェルマーの小定理を利用して法的逆元(逆数)を求めるアルゴリズム
30+
31+
a^(p-1) ≡ 1 (mod p) であることから、
32+
a * a^(p-2) ≡ 1 (mod p) となり、a^(p-2) が a の法的逆元となる。
33+
34+
[fermat](./fermat/)
35+
36+
### 実装例
37+
38+
- [] C
39+
- [] Python
40+
- [x] Haskell

math/fermat/fermat.hs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import Data.Int (Int64)
2+
3+
-- 法となる素数: 32 bit整数の最大値である2.1 * 10^9に近い
4+
modulus :: Int64
5+
modulus = 10 ^ 9 + 7
6+
7+
-- 繰り返し二乗法による (n^k) mod modulus の計算
8+
-- e.g. x^9の場合: x^2 = x * x
9+
-- x^4 = x^2 * x^2
10+
-- x^8 = x^4 * x^4
11+
-- x^9 = x * x^8
12+
powMod :: Int64 -> Int64 -> Int64
13+
powMod _ 0 = 1
14+
powMod n k
15+
| even k =
16+
let half = powMod n (k `div` 2)
17+
in (half * half) `mod` modulus
18+
| otherwise = (n * powMod n (k - 1)) `mod` modulus
19+
20+
-- フェルマーの小定理を用いた逆元計算
21+
-- a^(p-2) mod p
22+
invMod :: Int64 -> Int64
23+
invMod 0 = error "inverse of 0"
24+
invMod a = powMod a (modulus - 2)
25+
26+
main :: IO ()
27+
main = do
28+
let a = 3
29+
let invA = invMod a
30+
print invA
31+
print $ (a * invA) `mod` modulus -- フェルマーの小定理より1になるはず。

0 commit comments

Comments
 (0)