Challenge Factorialize Number - Using Arrays

Challenge Factorialize Number - Using Arrays
0

#1

Hello this is one of my first post in the forum. As many of you I am learning code and I got to the yucky part of algorithms in javascript. I’m in the factorialize a Number challenge but I went to a path the uses arrays to find the factorial. I know there are better and simpler ways to solve this problem but for now I want to stick to the array way. First I wanted to create an array of elements then after getting this array elements I wanted to use the reduce method.

This is my code so far:

function factorialize(num) {
//Decrement from 5 to 0
var numArray = [];
for (i = num; i > 0; i–){
numArray.push(i);
}
//Get decrement Array
return numArray;

//Multiply array elements
var multiplyArrays = numArray.reduce(function(a, b) {
return a * b;
}, 0);

}

In the part multiplyArray I get an error saying “unreachable var after return”. What does it mean? What do I need to do make the reduce method work?

Thanks for all your help here.


#2

I am not seeing the error you mentioned. To solve this problem, you only need to:

  1. Remove line #9

  2. Change the zero on line #14 to a one

  3. Add a return multiplyArrays at the end of factorialize function


#3

Thank you so much! It solved my function, but didn’t we need to retrieve the return numArray to use it later in the next multiplyArrays?


#4

One more time:
In order to pass the challenge, how can make pass 0 to return 1 to pass the challenge still using arrays.


#5

You still use numArray in the multiplyArrays reduce statement. You did not need the return statement though, because that was going to kick you out of the function right after the for loop and simply return the array called numArray.

One way to deal with 0! is to just return 1 if given 0 at the beginning of your factorialize function.


#6

where is the problem???

function factorialize(num) {
var c=1;
while(c<=num){
num=num*c;
c++;
}
return num;
}


#7

Your num was changed during the process. And it couldnt work for the loop. Consider this code.
function factorialize(num) {
var c=1;
while(num>=1){
c=c*num;
num–;
}
num=c;
return num;
}

We used the c for factorializing, num is just a loop condition.


#8

yup thanks …
then why is c assigned to num?


#9

Because finally it returns the num, and the num is out of the loop at that time.