Category talk:Wren-long: Difference between revisions
→Source code: Fixed an overflow problem with isPrime method.
(→Source code: Constructors no longer permitted to return values so changed to static methods instead.) |
(→Source code: Fixed an overflow problem with isPrime method.) |
||
Line 199:
}
return true
}
// Private helper method which returns 'a' * 'b' modulo 'mod' with less risk of overflow.
static modMul_(a, b, mod) {
var c = b.copy()
var x = ULong.zero
var y = a
while (c > ULong.zero) {
if ((c & 1) == 1) x = (x + y) % mod
y = (y << 1) % mod
c = c >> 1
}
return x
}
Line 369 ⟶ 382:
// Returns true if the current instance is prime, false otherwise.
// Fails due to overflow on numbers > 9223372036854775807 unless divisible by 2,3 or 5.
isPrime {
var isbp = ULong.isBasicPrime_(this)
if (isbp != null) return isbp
if (this > ULong.largest/2) Fiber.abort("Cannot test %(this) for primality.")
return ULong.millerRabinTest_(this, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37])
}
Line 621 ⟶ 636:
while (!exp.isZero) {
if (base.isZero) return ULong.zero
if (exp.isOdd) r = ULong.modMul_(r
exp = exp >> 1
base =
}
return r
|