Category talk:Wren-math: Difference between revisions
Content added Content deleted
m (→Source code: Minor bug fix.) |
(→Source code: Fixed a problem with Int.modMul, added Int.nextPrime2 method.) |
||
Line 230: | Line 230: | ||
if (a.count == 2) return l |
if (a.count == 2) return l |
||
return lcm(a[2..-1] + [l]) |
return lcm(a[2..-1] + [l]) |
||
} |
|||
// Private helper method for modMul method. |
|||
static checkedAdd_(a, b, c) { |
|||
var room = c - 1 - a |
|||
⚫ | |||
⚫ | |||
} else { |
|||
a = b - room - 1 |
|||
} |
|||
return a |
|||
} |
} |
||
Line 237: | Line 248: | ||
var sign = x.sign * n.sign |
var sign = x.sign * n.sign |
||
var z = 0 |
var z = 0 |
||
⚫ | |||
⚫ | |||
m = m.abs |
m = m.abs |
||
x = x.abs % m |
|||
n = n.abs % m |
|||
if (n > x) { |
|||
var t = x |
|||
x = n |
|||
n = t |
|||
} |
|||
while (n > 0) { |
while (n > 0) { |
||
if (n % 2 == 1) z = (z |
if (n % 2 == 1) z = checkedAdd_(z, x, m) |
||
x = (x |
x = checkedAdd_(x, x, m) |
||
n = div(n, 2) |
n = div(n, 2) |
||
} |
} |
||
Line 349: | Line 365: | ||
} |
} |
||
// Returns true if |
// Returns true if 'n' is prime, false otherwise but uses the |
||
// Miller-Rabin test which should be faster for |
// Miller-Rabin test which should be faster for 'n' >= 2 ^ 32. |
||
static isPrime2(n) { |
static isPrime2(n) { |
||
if (!n.isInteger || n < 2) return false |
if (!n.isInteger || n < 2) return false |
||
Line 417: | Line 433: | ||
while (true) { |
while (true) { |
||
if (Int.isPrime(n)) return n |
if (Int.isPrime(n)) return n |
||
n = n + 2 |
|||
} |
|||
} |
|||
// As 'nextPrime' method but uses 'isPrime2' rather than 'isPrime'. |
|||
// Should be faster for 'n' >= 2 ^ 32. |
|||
static nextPrime2(n) { |
|||
if (n < 2) return 2 |
|||
n = (n%2 == 0) ? n + 1 : n + 2 |
|||
while (true) { |
|||
if (Int.isPrime2(n)) return n |
|||
n = n + 2 |
n = n + 2 |
||
} |
} |