Factoralize a Number in JavaScript

吃可爱长大的小学妹 提交于 2019-12-06 11:26:20

There is two ways of doing that. First one in the loop and second one is in recursive function.

Loop version is like that:

function factorialize(num) {

  for(var answer=1;num>0;num--){
    answer*=num;
  }

  return answer;
}

And recursive one is like that.

function factorialize(num) {

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

Both of them will work with all positive integers.

function factorialize(num) {
    var myNum = 1;
    for (i=1; i<=num;i++){
        myNum = myNum * i;
    }
    return myNum;
}
factorialize(5);

First I created a var to hold our answer (myNum).

Then I created a loop that started at 1 and up to (and including) the value of the number we are factorializing... As the loop runs, we multiply myNum to the value of i, saving the new value as myNum, so it will be multiplied by the next number in the loop...

Once the loop has finished, we return our answer using the "return myNum".

Note: This response explains which type of loop to use and hints on how to format the loop to get a factorial of 5, to get the basic format before using num

Given the example of 5! = 1 * 2 * 3 * 4 * 5 = 120, you can see there is a pattern of numbers that start at 1, end at 5, and increment by 1. You can also see that for each number between 1 and 5, you need to multiply by the next one, over and over again, in order to get the factorial.

A for loop is used to repeat a specific block of code a known number of times. In this case, you know the number of times is 5 (aka 1,2,3,4,5). The specific block of code is what you'll need to figure out based on the answer you are trying to get (which in this case is 5! = 1*2*3*4*5 = 120).

For Loop Hints: When thinking about how to write the for loop's conditions: Start the incrementing at 1, end the incrementing at 5, and increment by 1 (1,2,3,4,5)

When writing the block of code that will act upon each number, think about the relationship each number needs to have so your code essentially does this: 1*2*3*4*5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!