Category talk:Wren-math: Difference between revisions
Content added Content deleted
(Added modMul, modPow, modInv and isPrime2 (using Miller-Rabin) methods to Int class.) |
(Added efficient divisorSum, divisorCount and reverse methods to Int class.) |
||
Line 655: | Line 655: | ||
var c = d.count |
var c = d.count |
||
return (c <= 1) ? [] : d[0..-2] |
return (c <= 1) ? [] : d[0..-2] |
||
} |
|||
// Returns the sum of all the divisors of 'n' including 1 and 'n' itself. |
|||
static divisorSum(n) { |
|||
if (!n.isInteger || n < 1) return 0 |
|||
var total = 1 |
|||
var power = 2 |
|||
while (n % 2 == 0) { |
|||
total = total + power |
|||
power = 2 * power |
|||
n = div(n, 2) |
|||
} |
|||
var i = 3 |
|||
while (i * i <= n) { |
|||
var sum = 1 |
|||
power = i |
|||
while (n % i == 0) { |
|||
sum = sum + power |
|||
power = i * power |
|||
n = div(n, i) |
|||
} |
|||
total = total * sum |
|||
i = i + 2 |
|||
} |
|||
if (n > 1) total = total * (n + 1) |
|||
return total |
|||
} |
|||
// Returns the number of divisors of 'n' including 1 and 'n' itself. |
|||
static divisorCount(n) { |
|||
if (!n.isInteger || n < 1) return 0 |
|||
var count = 0 |
|||
var prod = 1 |
|||
while (n % 2 == 0) { |
|||
count = count + 1 |
|||
n = div(n, 2) |
|||
} |
|||
prod = prod * (1 + count) |
|||
var i = 3 |
|||
while (i * i <= n) { |
|||
count = 0 |
|||
while (n % i == 0) { |
|||
count = count + 1 |
|||
n = div(n, i) |
|||
} |
|||
prod = prod * (1 + count) |
|||
i = i + 2 |
|||
} |
|||
if (n > 2) prod = prod * 2 |
|||
return prod |
|||
} |
} |
||
Line 710: | Line 760: | ||
static digitalRoot(n, b) { digitalRoot(n, b, false) } |
static digitalRoot(n, b) { digitalRoot(n, b, false) } |
||
static digitalRoot(n) { digitalRoot(n, 10, false) } |
static digitalRoot(n) { digitalRoot(n, 10, false) } |
||
// Returns a new integer formed by reversing the base 10 digits of 'n'. |
|||
// Works with positive, negative and zero integers. |
|||
static reverse(n) { |
|||
var m = (n >= 0) ? n : -n |
|||
var r = 0 |
|||
while (m > 0) { |
|||
r = 10*r + m%10 |
|||
m = div(m, 10) |
|||
} |
|||
return r * n.sign |
|||
} |
|||
// Returns the unique non-negative integer that is associated with a pair |
// Returns the unique non-negative integer that is associated with a pair |