每日一道算法题 - 阶乘 (easy-2)

虽然都是很简单的算法,每一个都只需5分钟左右,但写起来总会遇到不一样的小问题,但愿你们能跟我一块儿天天进步一点点。
更多的小算法练习,能够查看个人文章。javascript

规则

Using the JavaScript language, have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it (e.g. if num = 4, return (4 3 2 * 1)). For the test cases, the range will be between 1 and 18 and the input will always be an integer. java

使用JavaScript语言,让函数FirstFactorialnum)获取传递的num参数并返回它的阶乘(例如,若是num = 4,则返回(4 3 2 * 1))。
ps:对于测试用例,范围将介于1和18之间,输入将始终为整数。算法

测试用例

Input:4
Output:24

Input:8
Output:40320

my code

function FirstFactorial(num) { 
    var count = 1
    for(var i=num;i>0;i--) {
        count *= i
    }
  // code goes here  
  return count; 
}

other code

code 1

function FirstFactorial(num) {
  if (num === 0 || num === 1) {
    return 1;
  }
  return num * FirstFactorial(num - 1);   
}

code 2

function FirstFactorial(num) { 
    return ( num === 0 || num === 1) ? num : num * FirstFactorial(num - 1)
}

思路

方法1:经过遍历,计算出乘积
方法2:经过递归函数,计算出乘积函数

相关文章
相关标签/搜索