Skip to content

Commit

Permalink
Implement integer modular exponentiation using BigInteger#mod_pow
Browse files Browse the repository at this point in the history
  • Loading branch information
skateman committed May 10, 2020
1 parent e8270af commit 6ac22bc
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Compatibility:
Performance:

* Enable lazy translation from the parser AST to the Truffle AST for user code by default. This should improve application startup time (#1992).
* Implement integer modular exponentiation using `BigInteger#mod_pow` (#1999)

# 20.1.0

Expand Down
13 changes: 13 additions & 0 deletions src/main/java/org/truffleruby/core/numeric/IntegerNodes.java
Original file line number Diff line number Diff line change
Expand Up @@ -1755,6 +1755,19 @@ protected int getLimit() {

}

@Primitive(name = "mod_pow", lowerFixnum = { 0, 1, 2 })
public abstract static class ModPowNode extends PrimitiveArrayArgumentsNode {
@Child private FixnumOrBignumNode fixnumOrBignum = new FixnumOrBignumNode();

@Specialization
protected Object mod_pow(Integer base, Integer exponent, Integer modulo) {
BigInteger result = BigInteger
.valueOf(base)
.modPow(BigInteger.valueOf(exponent), BigInteger.valueOf(modulo));
return fixnumOrBignum.fixnumOrBignum(result);
}
}

@CoreMethod(
names = "downto",
needsBlock = true,
Expand Down
3 changes: 2 additions & 1 deletion src/main/ruby/truffleruby/core/integer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,9 @@ def nobits?(mask)

def pow(e, m=undefined)
return self ** e if Primitive.undefined?(m)
raise TypeError, '2nd argument not allowed unless a 1st argument is integer' unless Primitive.object_kind_of?(e, Integer)
raise TypeError, '2nd argument not allowed unless all arguments are integers' unless Primitive.object_kind_of?(m, Integer)
(self ** e) % m
Primitive.mod_pow(self, e, m)
end

def times
Expand Down

0 comments on commit 6ac22bc

Please sign in to comment.