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

虽然都是很简单的算法,每个都只需5分钟左右,但写起来总会遇到不同的小问题,希望大家能跟我一起每天进步一点点。
更多的小算法练习,可以查看我的文章。

规则

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.

使用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:通过递归函数,计算出乘积

    原文作者:an_l
    原文地址: https://segmentfault.com/a/1190000015574271
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞