Advertisement
Guest User

Untitled

a guest
Mar 31st, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. #include "ruby.h"
  2.  
  3. #define TO_BIGNUM(x) (FIXNUM_P(x) ? rb_int2big(FIX2LONG(x)) : x)
  4.  
  5. static VALUE zero = INT2NUM(0);
  6. static VALUE one = INT2NUM(1);
  7.  
  8. static VALUE c_mod_pow(VALUE self, VALUE exp, VALUE mod){
  9.  
  10. VALUE result = one;
  11. VALUE base = self;
  12.  
  13. VALUE base_square;
  14. VALUE result_base;
  15.  
  16. while( NUM2INT(rb_big_cmp(TO_BIGNUM(exp), zero)) > 0 ){
  17.  
  18. if ( rb_num2int(rb_big_and(TO_BIGNUM(exp), one)) ){
  19. result_base = rb_big_mul(TO_BIGNUM(result), base);
  20. result = rb_big_modulo(TO_BIGNUM(result_base), mod);
  21. }
  22.  
  23. exp = rb_big_rshift(TO_BIGNUM(exp), one);
  24. base_square = rb_big_mul(TO_BIGNUM(base), base);
  25. base = rb_big_modulo(TO_BIGNUM(base_square), mod);
  26. }
  27.  
  28. return result;
  29. }
  30.  
  31. void Init_mod_pow(){
  32. rb_define_method(rb_cInteger, "mod_pow", c_mod_pow, 2);
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement