# I solved the Smallest Common Multiple challenge, but it was too long?

I’m grateful that I solved the challenge, but I feel like I did it the long way. How can I improve my code?

``````function smallestCommons(arr) {
let ran = []
let sorted = arr.sort((a,b) => a - b)
for (let i = sorted[0]; i <= sorted[1]; i++) {
ran.push(i);
}

function primeFactors(n) {
const factors = [];
let divisor = 2;

while (n >= 2) {
if (n % divisor == 0) {
factors.push(divisor);
n = n / divisor;
} else {
divisor++;
}
}
return factors;
}

let factors = []
for (let i = 0; i < ran.length; i++) {
if (ran[i] == 1) {
factors.push([1])
} else {
factors.push(primeFactors(ran[i]))
}
}

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0)

let final = []
let count = [];
for (let i = 1; i <= ran[ran.length - 1]; i++) {
for (let j = 0; j < factors.length; j++) {
if (countOccurrences(factors[j], i) > count) {
count = countOccurrences(factors[j], i)
}
}
final.push([i, count]);
count = 0;
}

let realFinal = []
for (let i = 0; i < final.length; i++) {
for (let j = 0; j < final[i][1]; j++) {
realFinal.push(final[i][0])
}
}

let superFinal = realFinal.reduce((a,b) => a * b, 1)
return superFinal;
}
``````

The divisors approach is an interesting one. I’d first compare it to the one here:

The biggest difference between solution 4 and yours is that they keep less intermediate values than you do.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}