-
Notifications
You must be signed in to change notification settings - Fork 6
/
modint.rb
184 lines (146 loc) · 2.58 KB
/
modint.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
require_relative './core_ext/modint.rb'
# ModInt
class ModInt < Numeric
class << self
def set_mod(mod)
raise ArgumentError unless mod.is_a?(Integer) && (1 <= mod)
$_mod = mod
$_mod_is_prime = ModInt.prime?(mod)
end
def mod=(mod)
set_mod mod
end
def mod
$_mod
end
def raw(val)
x = allocate
x.val = val.to_i
x
end
def prime?(n)
return false if n <= 1
return true if (n == 2) || (n == 7) || (n == 61)
return false if (n & 1) == 0
d = n - 1
d >>= 1 while (d & 1) == 0
[2, 7, 61].each do |a|
t = d
y = a.pow(t, n)
while (t != n - 1) && (y != 1) && (y != n - 1)
y = y * y % n
t <<= 1
end
return false if (y != n - 1) && ((t & 1) == 0)
end
true
end
def inv_gcd(a, b)
a %= b
return [b, 0] if a == 0
s, t = b, a
m0, m1 = 0, 1
while t != 0
u = s / t
s -= t * u
m0 -= m1 * u
s, t = t, s
m0, m1 = m1, m0
end
m0 += b / s if m0 < 0
[s, m0]
end
end
attr_accessor :val
alias to_i val
def initialize(val = 0)
@val = val.to_i % $_mod
end
def inc!
@val += 1
@val = 0 if @val == $_mod
self
end
def dec!
@val = $_mod if @val == 0
@val -= 1
self
end
def add!(other)
@val = (@val + other.to_i) % $_mod
self
end
def sub!(other)
@val = (@val - other.to_i) % $_mod
self
end
def mul!(other)
@val = @val * other.to_i % $_mod
self
end
def div!(other)
mul! inv_internal(other.to_i)
end
def +@
self
end
def -@
ModInt.raw($_mod - @val)
end
def **(other)
$_mod == 1 ? 0 : ModInt.raw(@val.pow(other, $_mod))
end
alias pow **
def inv
ModInt.raw(inv_internal(@val) % $_mod)
end
def coerce(other)
[ModInt(other), self]
end
def +(other)
dup.add! other
end
def -(other)
dup.sub! other
end
def *(other)
dup.mul! other
end
def /(other)
dup.div! other
end
def ==(other)
@val == other.to_i
end
def pred
dup.add!(-1)
end
def succ
dup.add! 1
end
def zero?
@val == 0
end
def dup
ModInt.raw(@val)
end
def to_int
@val
end
def to_s
@val.to_s
end
def inspect
"#{@val} mod #{$_mod}"
end
private
def inv_internal(a)
if $_mod_is_prime
raise(RangeError, 'no inverse') if a == 0
a.pow($_mod - 2, $_mod)
else
g, x = ModInt.inv_gcd(a, $_mod)
g == 1 ? x : raise(RangeError, 'no inverse')
end
end
end