Hello Everyone,
I am working to solve a coding challenge on codewars which is called Satisfying numbers. And Actullay I have more than 7 failed test cases because of large values in some test cases.
So I want help to improvge my code so I can deal with these large values.
My code so far:
function smallest(n) {
let arrOfN = [];
for (let i = 1; i <= n; i++) {
arrOfN.push(i);
}
let res = [];
let length = 10000000;
for (let i = 1; i <= length; i++) {
if (arrOfN.every((num) => i % num === 0)) {
return i;
}
}
return;
}
Keep the factors function unchanged from my post, and use a separate loop in the smallest function that loops through the numbers from 1 to 10. Inside of that loop call the factors function, adding the result to an array.
well for starters, n = 1 should return 1, because 1, while not prime, is the basis for all of the math to follow. Start from 1, and find the value.
Also, the function is expecting you to return a number, not an array.
How did we turn
into this?
Personally, i’d rework the factors function a bit, to return what we’re actually interested in (not just an array of factors, but counts of the numbers.)
That’s because we are dealing with prime numbers. 4 is not a prime number. The number 4 is instead represented as 2*2 which appears as two lots of 2 in the list.
Yes, that’s a demonstration of how the answer is derived, but in the code you would instead use a loop to work through each of the prime numbers to the power of how many times they are used, and multiply those together to get the answer.
For the record, what we’re suggesting here is a mathematical principle - it’s a Least common multiple test, with all of the numbers from 1 (or really 2, because 1 is a divisor of EVERY integer…) to N. Specifically, we’re using the “Using prime factorization” method.