I know several languages, not Ruby. It seems that everyone who does eliptic curves uses Ruby and I am trying to understand this function. I have done multiple searches and not found the first question. Here is the code.
def inverse(a, m = $p)
m_orig = m # store original modulus
a = a % m if a < 0 # make sure a is positive
y_prev = 0
y = 1
while a > 1
q = m / a
y_before = y # store current value of y
y = y_prev - q * y # calculate new value of y
y_prev = y_before # set previous y value to the old y value
a_before = a # store current value of a
a = m % a # calculate new value of a
m = a_before # set m to the old a value
end
return y % m_orig
end
In the definition is (a, m = $p ) What the purpose of m = $p
I don’t see the origin of $p or its use in the code. m gets something, I don’t know what.
Second line of code is:
a = a % m if a < 0
Looks like:
replace a with the value of a %m, or a divided by me, integer divide and use the remainder. Cool.
Then the question / test: if a < 0.
If a is less than zero, then what?
If a is not less than zero, then what?
Edit: All the web pages I have been perusing are for elliptic curves. The arithmetic is 256 bit integer. This indicates that 512 precision is needed. How does Ruby know the length of the variables? And that the work is integer rather than float?
Edit 2: While thinking about the statement:
if a < 0
these thoughts come to mind:
if A == 0, I arithmetically that is ok, but is that possible for Elliptic curves?
if A < 0, is this possible in elliptic arithmetic? Does that event have any significance beyond just being a negative number?
Thank you for your time and patience.