# Bonfire: Factorialize a Number Solution

I’m going through FreeCodeCamp’s coding track as a way to brush up on Javascript, and re-familiarize myself with its more programming-centered features. I have been using Javascript primarily with websites. Most of the time, I’m not dealing with anything beyond timing, detecting user actions and maybe a little bit of animation. So and wanted to branch into more web application development. It’s also a good excuse to remind myself of programming practices without relying 100% on Swift–a language I’m still learning and is a few degrees more complex, versus doing it with Javascript–a language I’m more comfortable with.

I was cruising along fine with my skills map. A large proportion of the first few lessons centers around Codecademy’s online Javascript track. When I finished it up, FreeCodeCamp introduces the concept of Paired Programming and Bonfires. I decided to look into a couple of the the Bonfires on my own. The first three were pretty standard challenges. In fact, #1 and #2 weren’t actual challenges. #3 took a tiny bit of research and I had encountered it before while learning C++. Then I hit the fourth, where it tells you to Factorialize a Number. It was a great exercise that made me think outside of my comfort zone. After trying some really sloppy loops, I ended up with a recursive function.

I’m going to show both of my approaches to this one, first with the recursive function and second using a for loop. I’ve seen both approaches, and I’m by no means an expert at this. I just want to store my attempts at these challenges and walk through them to gain a better understanding. And if it helps someone else understand it too, then great!

### Let’s Factorialize a Number

The first thing I had to establish was what factorializing a number is actually about. The explanation was clear cut enough, but being a math dummy, I had to question myself every time I looked at it. And it was as simple as it seems. In laymans terms, when you factorialize a number, you are multiplying that number by each consecutive number minus one. So for example, if your number was 3. You would have something like this:

3! = 3 * 2 * 1

There’s a pretty easy pattern for this:

0! = 1
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1

And on and on, so by the time you reach, let’s say, 9 for example, you might have this:

9! = 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

Factorials are expressed in shorthand as x!, so when you see a number or value with an exclamation mark, you should know that we’re looking at factorials. Now that we kind of understand how that works, we can try to express that in code.

### Breaking It Down With a Math Dummy

I said it before, and it needs to be said again. I am bad at math. Terrible at it. I don’t know if it’s because of the way math was taught to me, or what. But me and math don’t go well together. However, even if you are as terrible at math as I am, this one is solvable! So here’s how I broke it down. The Bonfire on FreeCodeCamp starts you off with this:

```function factorialize(num) {
return num;
}

factorialize(5);```

Right off the bat, you know they want you to factorialize 5. They also want this written inside of a function called “factorialize”. That’s stuff we already know. So here’s what I was thinking…

1. Since we are essentially looking at determining what num is and then multiplying it by each consecutive number minus one, that can expressed like this num(-1). We need to stop it when num is equal to 1 because going further means hitting 0.

2. In factorials, 0! is always 1. Because multiplying by 0 will frequently return 0, we need to have an exception to prevent that from occurring when the function runs. So we probably need an if conditional statement that checks for 0 and returns 1. Since the conditional will check for and weed out 0, anyway, it might prevent num(-1) from ever getting there.

3. I’ll weed out 0 with the if conditional first. Then deal with num(-1) in a recursive function–which is kind of a hairy exercise for people might be completely new to coding.

### Writing Out the Code

Let’s start by doing Step 1 under the break down above. I’m going to weed out the incidence of hitting 0 using an if conditional.

```function factorialize(num) {
if (num === 0) {
return 1;
}
}
```

That was the easy part. What this does is evaluate num. If it detects num is equal to 0 at any point, it will run the statement inside of the if conditional and return 1. Dealing with the recursive function next is where it gets tricky. Though the code is minimal, sometimes the most minimalist of things are the most complicated.

```function factorialize(num) {
if (num === 0) {
return 1;
}
return num * factorailize(num-1);
}```

Oh boy, recursive functions. This is something I see in Swift and it always makes me go cross-eyed. Recursive functions run inside of themselves. So you might run a non-recursive function and it spits out a return value and you move on with your life. If you run a recursive function, it spits out a value that gets run again within the function, spits out another value which then gets run again in the function, spits out another and gets run again…on and on until it exits the recursion.

It’s hard to visualize this for me, but the best way is to remember sixth grade math and the order of operations (which, funny enough, is a core component of programming). Within the hallowed rule book of order of operations, you would perform the calculations inside of the parenthesis first. So if you had a formula like this:

(5 * 6) + 9 = n

You would do 5 * 6 first, then take the value you got from that and add 9 to get n. A similar thing is happening with our code. We are first taking num, subtracting 1, then using that value to multiply by num.

So if you had num set to 5, we would be returning this on factorialize()’s first pass:

5 * (5-1)

Second pass:

5 * (4-1)

Third pass:

5 * (3-1)

Fourth pass:

5 * (2 -1)

Fifth pass:

5 * (1-1)
return 1
5 * 1

During the fifth and final pass, our function falls into the if conditional. It returns 1 which num will multiply itself with and the function will exit with a total value.

In the case of factorialize(5). You should get 120. So, the final code all written out:

```function factorialize(num) {
if (num === 0) {
return 1;
}
return num * factorialize(num-1);
}

factorialize(5);```

We pass a parameter of 5 to factorialize(). It takes it into the function as num and checks if num is equal to 0. If num is equal to 0 it returns 1 and factorializes it as 5(1), where it will stop the recursion. If it’s not 0, it takes num and multiplies it by whatever num-1 is and continues to perform this action until num is equal to 0. The final return is the factorialization of the number 5 that we passed into factorialize(). That number should be 120.

### The For Loop Alternative

A for loop will also work as a solution to this Bonfire. There might be other solutions too, because a lot of problems in code can be solved multiple ways depending on style, approach and preferences. I just don’t know of any others. I had actually written a for loop that validates on Free Code Camp and technically does the same thing. I’ve seen others use this approach as well. Though it’s quite a bit more legwork. Here it is:

```function factorialize(num) {

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

factorialize(5);```

Above, we have a for loop within factorialize() that will continue to run so long as i remains greater than or equal to 1. In the above for loop, we make i equal to num -1. Then check if i is still greater than or equal to 1. If it is, then subtract 1 from i, and run the block of code. Within the block, we take num and multiply it by whatever i is. Then we return the result, which in this case should be 120.

More recently (or I could have just overlooked it), FreeCodeCamp added a check for 0 (thus foiling my plans) so I added an if conditional to check for 0 and return 1 if num === 0 ever evaluates to true. Thanks go out to Lena for bringing this to my attention in the comments.

I have a feeling there’s a more elegant way to express this in the For Loop so if you have alternatives or suggestions let me know!

### Resources

Bonfire: Factorialize a Number – luishendrix92
One of the more amusing explanations of what a recursive function is. This approach is pretty close to what I got, but it features a check for 1 as well as 0. I’m not sure if you really need that check for 1 and if I’m missing out on anything by not checking for 1 in my own solution. Or it could be another case of different approaches, different styles.

Posted

in

by

Tags:

### 16 responses to “Bonfire: Factorialize a Number Solution”

1. Nicole

Thank you so much! This was a great help:)

1. No problem, Nicole. Thank you for dropping by and leaving a message. 🙂

2. Lena

Hi Khanh!
In case with For Loop it did not help me. It actually checks for 0 and then returns it 0, unfortunately. What can we do about it in for loop? Does it mean that we can’t use it in this case?
Thank you for an article. Very helpful and interesting.

1. Hi Lena,

Thanks for dropping by :). Did FreeCodeCamp add the check for 0 more recently? I’m going to have to modify my post to keep up, so thank you so much for bringing this up! In the case of a 0 being fed into factorialize(), I would add an if conditional to weed it out. It might not be the cleanest solution, but it does resolve the issue:

function factorialize(num) {
for (var i = num – 1; i >= 1; i–)
num *= i;
// Add if conditional to check for 0 and return 1.
if (num === 0) {
return 1;
} else {
return num;
}
}
factorialize(5);

3. Nikola

Thank you so much man, awesome explanation! I was stuck as well. 🙂

1. Thank you for dropping by and leaving a comment, Nikola. I’m so glad this was helpful. 🙂

I also wish to thank you for your well written explanation at age 70 it has been a long time since maths class and they were so much different then however I am battling on in the hope that I may use any skills gained to help others.

1. Thank you for dropping by and leaving a comment, Adrian. I really appreciate hearing from everyone who find my posts helpful. Best of luck on your journey! 🙂

5. Gabrielle

Hi there,

Just wanted to say thanks for your tutorial. I’m new to coding and am going through FreeCodeCamp. I was having a hard time understanding the logic behind this lesson (Factorialize a Number Solution), and I’m glad I found your explanation because it’s well written and very clear. I wish you’d write one of these for every lesson!

Best,
Gabrielle

1. Hi Gabrielle,
Thanks for dropping by and leaving a comment. I’m glad this write-up was helpful and I do plan to continue writing solutions for each Bonfire as I get to it since it seems to be very helpful and a lot of individuals have expressed interest in seeing more. 🙂 Best of luck with your FCC journey!

2. Michael

Big thanks! I didn’t even know where to begin when I came across this challenge. I am completely new to coding, though I’ve flown through the program up until this point. Now I’m having to rely heavily on other sources. This article was a big, big help!

1. Thanks for leaving a message, Michael. I’m really glad this was able to help you! 🙂

3. Antonio Ho-Yen

I agree, I’m glad someone out here, realize that everyone doesn’t speak in technical terms.

“Learn how to teach, learn what to teach, so you can teach what you’ve learned~ “Yisrayl Hawkins”

1. I agree too, Antonio! Thank you for dropping by and leaving a message. 🙂