It's good to know you can do all recusive algorithms iteratively also, I had always wondered.
Your example above does not iterate unless you change n > 1 not n < 1, it had me going for a bit you and should always test your code ;-)
function factorial(num) {
let total = 1;
for(let n = num; n > 1; n--) {
total *= n;
}
return total;
}
Junior Developer at Interplay Learning - Feel free to contact me via LinkedIn or connect on Github, I am always happy to chat with folks from this community!
It's good to know you can do all recusive algorithms iteratively also, I had always wondered.
Your example above does not iterate unless you change n > 1 not n < 1, it had me going for a bit you and should always test your code ;-)
function factorial(num) {
let total = 1;
for(let n = num; n > 1; n--) {
total *= n;
}
return total;
}
Oops, thanks for pointing that typo out, I've made the change in the post.