Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
20
Task/Modular-inverse/Ruby/modular-inverse-1.rb
Normal file
20
Task/Modular-inverse/Ruby/modular-inverse-1.rb
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#based on pseudo code from http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2 and from translating the python implementation.
|
||||
def extended_gcd(a, b)
|
||||
last_remainder, remainder = a.abs, b.abs
|
||||
x, last_x, y, last_y = 0, 1, 1, 0
|
||||
while remainder != 0
|
||||
last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)
|
||||
x, last_x = last_x - quotient*x, x
|
||||
y, last_y = last_y - quotient*y, y
|
||||
end
|
||||
|
||||
return last_remainder, last_x * (a < 0 ? -1 : 1)
|
||||
end
|
||||
|
||||
def invmod(e, et)
|
||||
g, x = extended_gcd(e, et)
|
||||
if g != 1
|
||||
raise 'The maths are broken!'
|
||||
end
|
||||
x % et
|
||||
end
|
||||
12
Task/Modular-inverse/Ruby/modular-inverse-2.rb
Normal file
12
Task/Modular-inverse/Ruby/modular-inverse-2.rb
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
def modinv(a, m) # compute a^-1 mod m if possible
|
||||
raise "NO INVERSE - #{a} and #{m} not coprime" unless a.gcd(m) == 1
|
||||
return m if m == 1
|
||||
m0, inv, x0 = m, 1, 0
|
||||
while a > 1
|
||||
inv -= (a / m) * x0
|
||||
a, m = m, a % m
|
||||
inv, x0 = x0, inv
|
||||
end
|
||||
inv += m0 if inv < 0
|
||||
inv
|
||||
end
|
||||
2
Task/Modular-inverse/Ruby/modular-inverse-3.rb
Normal file
2
Task/Modular-inverse/Ruby/modular-inverse-3.rb
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
require 'openssl'
|
||||
p OpenSSL::BN.new(42).mod_inverse(2017).to_i
|
||||
Loading…
Add table
Add a link
Reference in a new issue