Category talk:Wren-big: Difference between revisions
Content added Content deleted
(→Source code: Added divisors and properDivisors methods to BigInt.) |
(→Source code: Added a second divisors method.) |
||
Line 1,480: | Line 1,480: | ||
} |
} |
||
// Returns all the divisors of 'n' including 1 and 'n' itself. |
// Returns all the divisors of 'n' including 1 and 'n' itself. |
||
static divisors(n) { |
static divisors(n) { |
||
if (n < |
if (n < 1) return [] |
||
if (n is Num) n = BigInt.new(n) |
|||
var divs = [ |
var divs = [] |
||
var divs2 = [] |
|||
var i = one |
|||
var k = (n.isEven) ? one : two |
|||
var sqrt = n.isqrt |
|||
while (i <= sqrt) { |
|||
if (n.isDivisibleBy(i)) { |
|||
divs.add(i) |
|||
var j = n / i |
|||
if (j != i) divs2.add(j) |
|||
} |
|||
i = i + k |
|||
} |
|||
if (!divs2.isEmpty) divs = divs + divs2[-1..0] |
|||
return divs |
|||
} |
|||
// Returns all the divisors of 'n' excluding 'n'. |
|||
static properDivisors(n) { |
|||
var d = divisors(n) |
|||
var c = d.count |
|||
return (c <= 1) ? [] : d[0..-2] |
|||
} |
|||
// As 'divisors' method but uses a different algorithm. |
|||
// Better for large numbers with a small number of prime factors. |
|||
static divisors2(n) { |
|||
if (n <= zero) return [] |
|||
var factors = primeFactors(n) |
|||
var divs = [one] |
|||
for (p in factors) { |
for (p in factors) { |
||
for (i in 0...divs.count) divs.add(divs[i]*p) |
for (i in 0...divs.count) divs.add(divs[i]*p) |
||
Line 1,498: | Line 1,527: | ||
} |
} |
||
// |
// As 'properDivisors' but uses 'divisors2' method. |
||
static |
static properDivisors2(n) { |
||
var d = |
var d = divisors2(n) |
||
var c = d.count |
var c = d.count |
||
return (c <= 1) ? [] : d[0..-2] |
return (c <= 1) ? [] : d[0..-2] |
||
} |
} |
||
} |
} |
||