Factorialize number help

Hey guys, taking on the advice not to look up solutions, I looked into recursion again and came up with the equation below. It seems there’s no loop going on though as it just returns 5 * 4 once, rather than 54321.

What am I missing? Thanks

Your code so far


function factorialize(num) {
while (num > 0)
  return num * (num-1);
}

console.log(factorialize(5));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36.

Challenge: Factorialize a Number

Link to the challenge:

Hi @am93 !

I think it would help if you say outloud what your code is doing.

Your code translation:

While 5 is greater than 0 return 5 times (5-1).

So the computer is doing what you told it to do.

Remember that recursion is a function that calls itself.
Also, recursion should have a base case so it doesn’t keep calling itself.

Yeah actually read it to myself

I don’t know what a base case would be. I found this to help me get to where I am Recursion - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

I can easily look up a solution to this but I’m trying not to. So guys sorry if you see me post a question for almost all the algorithm questions

Well I think what would help would be to write down on paper what you are trying to do before diving into code.

To find the factorial of 5 it would be 5*4*3*2*1.

You could also rewrite that as the factorial of 5 is 5 * factorial(4)
the factorial of 4 is 4 *factorial(3).
Etc,etc,etc.

At some point we are going to have to stop because you can’t have the factorial of negative -55 right.

By definition, the factorial is the product of positive numbers.

So try with pen and paper to solve the factorial of 5.
Then you can think about a good base case. When num equals blank then we can stop the recursion.

I think working it out on paper and understanding how factorials work will help you create a base case and recursive case.

1 Like

It’s because there is no recursion in your function. A recursive function calls itself but you aren’t calling factorialize() in the function body.

This is just a loop, and your loop doesn’t do anything accept return whatever the number is multiplied by that number minus one.

So:

  • you’ve used a while loop
  • returning from a function ends a function
  • you haven’t done anything with num: if you didn’t return and stop the function, this would just go on looping forever.

So maybe review how for/while loops work, how you write them, as there are basic issues here.

As it is, if you’re asking about recursive functions, that means solving a problem by solving progressively smaller problems via a function calling itself. For example,

What is the factorial of 5?
The factorial of 5 is 5 × the factorial of 4.
What is the factorial of 4?
The factorial of 4 is 4 × the factorial of 3.
What is the factorial of 3?
The factorial of 3 is 3 × the factorial of 2.
What is the factorial of 2?
The factorial of 2 is 2 × the factorial of 1.
What is the factorial of 1?
The factorial of 1 is 1 × the factorial of 0.
What is the factorial of 0?
The factorial of 0 is 1 (this is the base case)
1 × 1 is 1
2 × 1 is 2
3 × 2 is 6
4 × 6 is 24
5 × 24 is 120

So

What is the factorial of n?
The factorial of n is n × the factorial of n - 1, unless n is 0, at which point the value is 1.

It’s either a loop of a recursive function for this, and they’re interchangeable things.

while (num > 0) {
          ↑
       is a base case
for (let i = num; i > 0; i--) {
                    ↑
              is a base case
if (num === 0) {
        ↑
 this is the base case
  return 1;
} else {
1 Like

Thanks for explaining what a factorial is. I’m not good with these terms. For example I didn’t know what initialize was until recently even though I knew what the action was.

The reason I wrote just n > 0 vs the regular (let i = 0; i < 0; i++) is because I peeked at the first line explained here Three Ways to Factorialize a Number in JavaScript and thought I should try the rest on my own. It turns out maybe they are solving a different way.

I just went ahead and looked up the solution and will use

function factorialize(num) {
  for (var i = 1; num > 0; num--) {
  i *= num;
  }
  return i;
}

What determines when to use (var i = x..) or (let i =x...)?

Does anyone know where else I can find more practice problems like this?

What determines when to use (var i = x..) or (let i =x...) ?

They are roughly equivalent, var being the older form. There are some slight differences. If you search on google you can find many explanations about the differences of let and var (and const).

In this case, since you are using the index variable (i) outside the scope of the for loop, you would either have to use var or make a few changes.

1 Like

Does anyone know where else I can find more practice problems like this?

There are a lot of algorithm challenges in FCC. There are also sites with a lot of them, like leetcode or codewars.

1 Like

I think that it’s worth pausing to think about what’s the information you would have wanted in order to keep problem solving instead of looking at the solution and what questions might you have asked to help you get that information.

@kevinSmith Ok so just to be clear, it’s both usable unless i is outside the scope of the for loop. In this case that is return i?

The let i = 1 input wasn’t working on this one.

@JeremyLT agreed. This is a point where I start to struggle. When I read this problem I knew I could use a for loop, but then I wasn’t able to figure out I needed var i = 1, but knew I would need to decrease 1 starting at num.

I tried looking at a line of solution to get an idea, but wasn’t able to make it work so I wrote this post. After a while I wasn’t able to understand what to do, and eventually I felt waiting even longer and struggling without progress may be worse then understanding a solution.

Maybe I could just write that I don’t know how to start something then get the lead that way? I’m currently googling how to for example get the length of a string, then trying to write the function. What would you suggest I do?

Yeah, I totally understand that feeling. It can really suck to feel frustrated and struggle and not feel like you are making progress. I have some problems at work that I’m really frustrated with right now and progress is painfully slow.


In this case, I would start with a skeleton of what you think the code might look like. You said a loop. Well, I’d start with that

function factoralize(num) {
  for (let i = 0; i < num; i++) { // Loop bounds 0 to num I guess?
    // Ok, I think I need a loop,
    //  but I don't know how to make this loop 'do' the magic
  }
  return magic; // Need to return something magical
}

It is totally ok to write some super broken code with comments. This is not much more than what your first instinct was, but we can help you fill stuff in.
In this case, you’d get a compile error, and would probably have this as a next step:

function factoralize(num) {
  let magic = 1; // Need to declare the 'something magical' for the code to run
  // Note: probably need a better variable name
  for (let i = 0; i < num; i++) { // Loop bounds 0 to num I guess?
    // Ok, I think I need a loop,
    //  but I don't know how to make this loop 'do' the magic
  }
  return magic; // Need to return something magical
}

With this we can start to talk about how that loop can make a factorial or if there is a different logical or control structure to consider.


If you want, we can use your version of something similar to build up to the solution.

1 Like

Hi again!

For extra algorithm practice, you can try the sites mentioned above.

I really like codewars the best but leetcode is good to. You could also try hackerrank.

If you are going to do codewars start with the 8kyu problems. That is the beginner level.

1 Like

Thanks. I’ll start doing that and include it to my questions on this forum. I know @jwilkins.oboe also suggested this but didn’t think to include it in my posts.

Just curiuous what do you mean by this?

I meant that you know where this solution ends up but we can still practice transforming this rough skeleton of code to a final solution if you are interested. There is already one bug with that skeleton that I just realized.

Also, I am not sure if I shared about writing out your process before diving into code using pseudocode. pseudocode

The more planning you can do before coding the better.

Yeah sure why not. I better get this down good to prevent future issues.

Separately I used your suggestion on the following problem and made a post on it. Let me know if this is what you meant :grin:What am I missing with this string length?

I’m going to completely stop looking up solutions to make sure I truly learn. I’ll only look at the hints and consult on the forum. Not gonna lie though it’s really tempting when I feel like I’m close to the answer lol

It’s a matter of scope. One of the differences between var and let is how they are scoped - one is function level scoping and the other is block level scoping. Any let inside the for statement is scoped only to that code block:

  for (let i = 1; num > 0; num--) { // scope of i begins on this line
    i *= num;
  }                                 // scope of i ends here
  return i;                         // i is undefined here

But var is a little “sloppier” - it is scoped for the whole function, even if declared in an inner code block.

If you wanted to use i outside that code block and still use let, you’d have to declare it before the for loop:

  let i.    // declared in the code block of the function so it will be in scope anywhere in this function
  for (li = 1; num > 0; num--) { 
    i *= num;
  }                               
  return i;             

There are other solutions, but this is inline with your question.