Tell us what’s happening:
So the code is giving me:
[ 1, 2, 3, 2, 5, 1, 7, 2, 3, 1, 11, 2, 13 ]
in prod.
The second last element i.e. 2 should be 1 because 12=223 are already counted. However, due to the way, I’m checking my while(!isPrime(prod[i]))
it stops diving prod[i]
when it reaches 2 or 3 or whatever prime, but I want it to go all the way to 1.
P.S.: I know it can be done by counting the number of primes and multiplying. I’m wondering if there’s a way like this
Your code so far
function smallestMult(n) {
let prod=[...Array(n).keys()].map(i=>i+1)
let prod2=[...Array(n).keys()].map(i=>i+1)
for(let i=n-1; i>=0; i--)
do
for(let j=i-1; j>=0; j--)
if(prod[i]%prod2[j]==0 && isPrime(prod2[j]))
{
prod[i]/=prod2[j]
}
while(!isPrime(prod[i]))
let product=1
for(let i=0; i<n; i++)
product*=prod[i]
console.log(prod)
return product
}
function isPrime(n) {
for(let i=2; i<n; i++)
if(n%i==0)
return false
return true
}
smallestMult(13);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
.
Challenge: Problem 5: Smallest multiple
Link to the challenge: