Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created April 25, 2015 02:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/bcbd785acda1bc2abb69 to your computer and use it in GitHub Desktop.
Save komasaru/bcbd785acda1bc2abb69 to your computer and use it in GitHub Desktop.
Ruby script to compute modular-exponentiation iteratively.
#!/usr/local/bin/ruby
#*************************************
# Modular Exponentiation (iterative).
#*************************************
class ModularExponentiation
def comp_mod_exp(b, e, m)
ans = 1
while e > 0
ans = (ans * b) % m if (e & 1) == 1
e >>= 1
b = (b * b) % m
end
return ans
rescue => e
raise
end
end
exit unless __FILE__ == $0
begin
# me = b^e mod m
b, e, m = 12345, 6789, 4567
obj = ModularExponentiation.new
me = obj.comp_mod_exp(b, e, m)
puts "#{b}^#{e} mod #{m} = #{me}"
rescue => e
puts "[#{e.class}] #{e.message}"
e.backtrace.each{ |bt| puts "\t#{bt}" }
exit 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment