Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to power and mod in ruby

Tags:

ruby

i need to know the value of an power and mod of 3 values, such as:

print 1_299_709 ** 1_300_751 % 104_729

was there any ruby gems or faster way to compute this using ruby?

like image 984
Kokizzu Avatar asked Feb 09 '13 05:02

Kokizzu


People also ask

What is the modulo method in Ruby?

Method The modulo () is an inbuilt method in Ruby returns the modular value when two numbers are divided. It returns the value of a modulo b. Parameters: The function needs two number whose modulus on division is returned.

How to convert between number systems in Ruby?

You can convert between number systems in Ruby with the to_s method. Here’s how to convert from decimal ( 9) to binary ( 1001 ): You can use the to_i method on a string to convert back into an integer. So if you want to go from hexadecimal ( ff) to decimal ( 255) you can do this: Where 16 is the “symbol count” or base for the number.

How do you use operators in Ruby?

Ruby - Operators. Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument. For each operator (+ - * / % ** & | ^ << >> && ||),...

What is the use of exponent and operator in Ruby?

Exponent AND assignment operator, performs exponential (power) calculation on operators and assign value to the left operand. Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example − This may be more quickly declared using parallel assignment −


2 Answers

This is called modular exponentiation and is used heavily in cryptography. Its fairly easy to write a modular exponentiation algorithm, a demonstration is in the wikipedia article listed above.

You can use the standard library openssl to achieve your goal:

require 'openssl'
1_299_709.to_bn.mod_exp(1_300_751, 104_729) # => 90827
like image 86
Daniel Evans Avatar answered Sep 21 '22 06:09

Daniel Evans


Since Ruby 2.5 modular exponentiation is built in:

print 1_299_709.pow(1_300_751, 104_729)
like image 28
steenslag Avatar answered Sep 20 '22 06:09

steenslag