/** * Return array of prime factors (in ascending order) of n. * * We will represent even powers of 2 as 4, for ease of plotting * * Examples: * primeFactors(1) = [] * primeFactors(10) = [2, 5] * primeFactors(5) = [5] * primeFactors(60) = [4, 3, 5] */ function primeFactors(n) { if (n < 1) throw "Argument error"; var result = []; while (n != 1) { var factor = getFactor(n); // call getFactor function result.push(factor); n /= factor; } return result; } /** * Return smallest prime factor of n. */ function getFactor(n) { if (n < 2) throw "Argument error"; if (n % 4 == 0) return 4; if (n % 2 == 0) return 2; for (var i = 3; i <= Math.floor(Math.sqrt(n)); i += 2) { if (n % i == 0) return i; } return n; } /** * Print string representation of array of prime factors * Examples * printFactors([4, 3, 5]) = "2 × 2 × 3 × 5" * printFactors([3, 5]) = "3 × 5" * printFactors([7]) = "prime" */ function printFactors(factors) { var string = ""; if (factors.length == 1) { string = factors[0] == 4 ? "2 × 2" : "prime"; return string; } factors.forEach(function(factor) { stringFactor = factor == 4 ? "2 × 2" : factor; string += stringFactor + " × "; }); return string.slice(0, -2); // remove last two characters }