Ruby code difficult to decode, help me properly translate ruby syntax

Viewed 52

extremely sorry for the somewhat lame title but that's as straightforward as I could phrase it....

I'm attempting to translate a piece of ruby code to c++.. So far others have compiled fine except this one.

I don't quite understand the meaning of lines such as

prevy, y = 0, 1

Does prevy = 1? If not where does the 1 belong?


y, prevy = prevy - q * y, y

I get that in the above prevy = prevy - q * y but what exactly is y, doing there? Same thing with the y after prevy = prevy - q * y What exactly is supposed to happen to the y?

a, m = m % a, a

Same questions apply to the above line.

If you take a closer look, every other line is pretty clear... From the if statement to the while loop

# RUBY CODE derived from https://learnmeabitcoin.com/technical/ecdsa#signing-step-5 implemented by Greg Walker aka in3rsha

def inverse(a, m = $p)
  m_orig = m         # store original modulus
  a = a % m if a < 0 # make sure a is positive
  prevy, y = 0, 1
  while a > 1
    q = m / a
    y, prevy = prevy - q * y, y
    a, m = m % a, a
  end
  return y % m_orig
end

// C++ VERSION OF RUBY FUNCTION
// BigInteger belongs to the C++ Big Integer library by Matt McCutchen at www.mattmccutchen.net/bigint/
// It has a straight forward implementation approach as well as easy to understand method calls and can also easily be combined as a single header file

BigInteger modInverse(BigInteger a, BigInteger m)
{
    BigInteger prevy, q, o_o, y; // DECLARE VARIABLES
    o_o = m; // create copy of initial starting point for later use     
    if(a<0) // if a is less than 0
        a = a % m; // mod a by m

    y = 0, prevy = 1; // set y = 0 and prevy = 1
    while(a>1) // while a is greater than 1
    {
        q = m / a; // Divide m by a and store result in q
        prevy = prevy - (q * y); // subtract prevy from the result of q * y
        m = m % a; // mod m by a
        // I'm i suppose to do a--; or a = m; next? 
        // Over here as well.. y--; or y = prevy;
    }
    y = y % o_o; // mod y by original initial starting point
    return y;
}

RUBY CODE derived from Learn Me a Bitcoin ECDSA Page implemented by Greg Walker aka in3rsha

BigInteger belongs to the C++ Big Integer Library by Matt McCutchen

0 Answers
Related