Skip to content

Commit

Permalink
Reuse extended_gcd for calculating inv in ModInt
Browse files Browse the repository at this point in the history
  • Loading branch information
hakatashi committed Sep 5, 2023
1 parent 95d143c commit 31b94af
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 15 deletions.
10 changes: 6 additions & 4 deletions src/math.cr
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ module AtCoder
# Implements [ACL's Math library](https://atcoder.github.io/ac-library/master/document_en/math.html)
module Math
def self.extended_gcd(a, b)
zero = a.class.zero
one = zero + 1

last_remainder, remainder = a.abs, b.abs
x, last_x, y, last_y = 0_i64, 1_i64, 1_i64, 0_i64
x, last_x, y, last_y = zero, one, one, zero
while remainder != 0
new_last_remainder = remainder
quotient, remainder = last_remainder.divmod(remainder)
last_remainder = new_last_remainder
quotient, new_remainder = last_remainder.divmod(remainder)
last_remainder, remainder = remainder, new_remainder
x, last_x = last_x - quotient * x, x
y, last_y = last_y - quotient * y, y
end
Expand Down
13 changes: 2 additions & 11 deletions src/mod_int.cr
Original file line number Diff line number Diff line change
Expand Up @@ -271,17 +271,8 @@ module AtCoder
end

def inv
x = value.to_i32
y = M.to_i32
u, v = 1, 0
while y > 0
t = x // y
x -= t * y
x, y = y, x
u -= t * v
u, v = v, u
end
self.class.new(u)
g, x = AtCoder::Math.extended_gcd(value.to_i32, M.to_i32)
self.class.new(x)
end

def to_s(io : IO)
Expand Down

0 comments on commit 31b94af

Please sign in to comment.