Scientific Calculator

(public) silentmatt/factors

By silentmatt Matthew Crumley

Get all the prime factors of a number (plus 0 or -1) with or without duplicates.

Tagged: number-theory primes

var factors = function(n) {
    n < 0 ?
        [-1 | factors(-n)]
    : n == 0 ?
        [0]
    : n == 1 ?
        []
    : (
        var res = [];
        while (n mod 2 == 0) -> (res[len res] = 2; n /= 2);
        var odd = 3;
        while (odd <= n) -> (
            (n mod odd == 0) ? (
                res[len res] = odd;
                n /= odd;
            )
            : (
                odd += 2;
            );
        );
        res;
    );
};

var distinctfactors = function(n) {
    var fs = factors(n);
    var ufs = [];
    var last = -2;
    var i = 0;
    while (i < len fs) -> (
        (fs[i] != last) and (ufs[len ufs] = last = fs[i]);
        i += 1
    );
    ufs
}

spam? | offensive?

2 Comments

Sign in to leave a comment