Can anyone help to understand "Factorialize a Number" challenge?

Can anyone help to understand "Factorialize a Number" challenge?
0

#1

Hello! I can’t understand why we need to add these conditions num<0 return -1 and num ==0 return 1?

function factorialize(num) {
  if (num < 0) 
        return -1;
  else if (num == 0) 
      return 1;
  else {
      return (num * factorialize(num - 1));
  }
}
factorialize(5);

#2

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.


#3

Hi Nikita,

Lets start understanding step by step

            1! = 1
 2! = 1!*2 
            2! = 2
 3! = 2!*3
            3! = 6
 4! = 3!*4
            4! = 24

We can turn this around:

            4! = 24
 3! = 4!/4
            3! = 6
 2! = 3!/3
            2! = 2
 1! = 2!/2
            1! = 1
 0! = 1!/1
            0! = 1

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 :sunglasses:

Especially Discrete Mathematics which is the backbone for a Software Engineer.

Hope this would be helpful.


#4

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;
}

#5

He starts with factorial = 1. Both 0! and 1! are 1, so those values don’t change factorial. You can therefore start with 2!

I would suggest having a look at the documentation: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Statements/for
n starts at 2 and its final value is 5.

Run the code. You will see that it does return 120.


#6

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.