Help! Basic Algorithm Scripting: Factorialize a Number (Using a While Loop)

Hello. I’m trying to complete this algorithm challenge (Factorialize a Number) using a while loop. Can anyone kindly tell me what I am doing wrong here?

function factorialize(num) {
var i = 1;
while (i <= num) {
num = num*(i);
i++;
}
return num;
}

factorialize(5); 

Your i will get values of 1,2,3,4,5 before the loop breaks (condition is I <= num and num is 5)

The starting value of num is 5

So at the end you are returning the result of 5*1*2*3*4*5

Thanks for pointing that out!
But my original code doesn’t even return a result, not even the wrong one.
I don’t know why…

Actually my browser crashes when I run that code

Ah, right, the reason it crashes is because you are changing num…

So your condition also changed:
i <= 5
But then you do num *= i
So the you have i <= 10 then i <= 30 etc
You have an infinite loop because the condition changes at each iteration

1 Like

For those wondering about the solution…

After some thinking, I realised that the solution is simpler than I thought:

function factorialize(num) {
var i = 1;
var answer = 1;
while (i <= num) {
answer *= i;
i++;
}
return answer;
}

And thanks again for your input @ilenia

@tamaranhj It is great that you figured it out, but in the future it is not necessary (and actually is preferred) that you not post a full working solution to the challenge.

Thanks

Sorry about that, kinda new here on the forums!

Thanks

The challenge doesn’t require a while loop, so you are in fact posting working solutions to the challenge. Please wrap the code blocks in spoiler tags so they get blurred.

Oh, the way OP worded it he was specifically speaking about a while loop, my bad. Dont even see my reply here anymore sooo guess someone doesn’t like helping others view problems in a different light so that they’re not always restricted to the same approach for every challenge.

PS: This recent form of strict moderation is not a very welcoming environment especially when solutions are shared as alternatives when OP has already solved the challenge. We should be open to new techniques and approaches and sharing different code to compare and improve.