R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Prime Factors}

The Problem

Given a positive number n (n > 0) find the prime factor decomposition of n. The result will be a string with the following form :

 "(p1**n1)(p2**n2)...(pk**nk)"

 

(p1**n1)

Prime factor

# of occurrences

IMPORTANT NOTES: 

- Prime factors should be returned in increasing order

- If a factor only occurs once, it should be represented   as "(p)" rather than "(p**1)"

Tests to Run

Input: 86240
Output: "(2**5)(5)(7**2)(11)"

Input: 80
Output: "(2**4)(5)" 

Input: 25
Output: "(5**2)"

Input: 293
Output: "(293)"
function primeFactor(n) {
    var repeats = 0,
        dividedNum = n,
        sqRoot = Math.sqrt(n);
    for (i = 2; i <= sqRoot; i++) {
        if (i % 2 || i === 2) {
            if (dividedNum % i === 0) {
                while (dividedNum % i === 0) {
                    repeats++;
                    dividedNum = dividedNum/i;
                }
                if (dividedNum === 1) return stringIt(i, repeats);
                else return stringIt(i, repeats) + primeFactor(dividedNum);
            }         
        }
    }
    return "(" + n + ")";
}

function stringIt(factor, repeats) {
    if (repeats === 1) {
        return "(" + factor + ")";
    } else {
        return "(" + factor + "**" + repeats + ")";
    }
}


// I refactored the function to be recursive. See next slide for Omri's solution,
// which also uses recursion.

Solution 1

function format (factors) {
    return factors.reduce(function (arr, n) {
        arr[n] = 1 + (arr[n] || 0);
        return arr;
    },[]).reduce(function (result, amount, n) {
        var amountFormat = amount < 2 ? '' : '**' + amount;
        return result + '(' + n + amountFormat + ')';
    }, '');
}

function primeFactors (n) {
    var root = Math.sqrt(n);
    for (var x = 2; x <= root; x++) {
        if (n % x === 0) {
            return [x].concat(primeFactors(n/x));
        }
    }
    return [n];
}

function theThing (n) {
    return format(primeFactors(n));
}

Solution 2

Reacto: Prime Factors

By Katie Peters

Reacto: Prime Factors

  • 1,562