Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two problems that are causing the segfault:</p> <p>1 - The functions <code>rb_big_*</code> sometimes doesn't return a <code>Bignum</code> object, but when you call then the first arg <strong>must</strong> be a <code>Bignum</code> object. For example:</p> <pre><code>if (rb_big_modulo(exp, CONST2BIGNUM(2))) { VALUE mul = rb_big_mul(res, base); // This maybe return a Fixnum res = rb_big_modulo(mul, mod); // This will cause a segfault :( } </code></pre> <p>2 - The function <code>rb_big_pow</code> when you call it with both args <code>Bignum</code>, it will warn you and will return a <code>Float</code> object where you can't convert easily to a <code>Bignum</code> object. So, you should replace the line where you call it by:</p> <pre><code>VALUE x = TO_BIGNUM(rb_big_pow(base, INT2NUM(2))); // Power by a Fixnum instead a Bignum base = TO_BIGNUM(rb_big_modulo(x , mod)); </code></pre> <p>The final implementation will be:</p> <pre><code>#define TO_BIGNUM(x) (FIXNUM_P(x) ? rb_int2big(FIX2LONG(x)) : x) #define CONST2BIGNUM(x) (TO_BIGNUM(INT2NUM(x))) VALUE method_big_power_mod(VALUE self, VALUE base, VALUE exp, VALUE mod){ VALUE res = TO_BIGNUM(INT2NUM(1)); base = TO_BIGNUM(base); exp = TO_BIGNUM(exp); mod = TO_BIGNUM(mod); while (rb_big_cmp(exp, CONST2BIGNUM(0))) { if (rb_big_modulo(exp, CONST2BIGNUM(2))) { VALUE mul = TO_BIGNUM(rb_big_mul(res, base)); res = TO_BIGNUM(rb_big_modulo(mul, mod)); } VALUE x = TO_BIGNUM(rb_big_pow(base, INT2NUM(2))); base = TO_BIGNUM(rb_big_modulo(x , mod)); exp = TO_BIGNUM(rb_big_div(exp, CONST2BIGNUM(2))); } return res; } </code></pre> <p>I don't know the performance impact with all these conversions. Maybe, you should test when it is a <code>Fixnum</code> or a <code>Bignum</code>and calculate it using the proper function or benchmark both approaches.</p> <p>When I ran it, I went thought an infinite loop, but I don't know if I call it with the correct values. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload