You don’t have to check for num < 0, though it might be a good idea to return somehting like -1 or undefined when the input is invalid.
You need the num == 0 because it is the last valid factorial (0! = 1). So if num == 0 it makes no sense to return (num * factorialize(num - 1)). That would run factorialize(-1) which does not exist.
If we try to extend this to -1, we find that (-1)! = 1/0 which means that (-1!) is undefined. Extending further to (-2)! etc. is thus impossible as well.
I would recommend you to execute the prog without the if (num < 0) condition and pass -1 as parameter and check what is the result. This is an exciting way to learn and understand the programming.
Remember, if you are good in Maths then its IMPOSSIBLE IMPOSSIBLE to beat you as a programmer/developer.
I am working on my Mathematics again
Especially Discrete Mathematics which is the backbone for a Software Engineer.
Thnak you. One more thing. In this example I can’t understand : he starts at 2(var n = 2) and add 1 to it(n++) then code is executed. So what we have is factorial = 1 * 3 (factorial = 1, n = 2++,total - 3),3 * 4 (total - 12), 12 * 5 (60). At the end it’s not equal to 120.
function factorialize(num) {
var factorial = 1;
for (var n = 2; n <= num; n++) {
factorial = factorial * n;
}
return factorial;
}
Sometimes odd inputs like a negative input in factorialize are called “corner cases” and in a “test-first” style of software development you brainstorm on all the unusual corner cases and write tests to make sure you catch those before actually writing code.