在JavaScript中使用Factthize数字 [英] Factoralize a Number in JavaScript

查看:128
本文介绍了在JavaScript中使用Factthize数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在参加免费守则训练营的课程,它要求我为任何给定的数字返回一个因子。但是,我有点坚持这个问题(请原谅我,数学不是我的强项,哈哈)。以下是它的要求:

I'm currently taking a course on Free Code Camp and it's asking me return a factorial for any given number. However, I'm kind of stuck on the question (please forgive me, math isn't my strong point, haha). Here's what it asks:


如果整数用字母n表示,则阶乘是所有正整数小于或等于的乘积到了
因子通常用简写符号n表示!例如:5! = 1 * 2 * 3 * 4 * 5 = 120f

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n. Factorials are often represented with the shorthand notation n! For example: 5! = 1 * 2 * 3 * 4 * 5 = 120f

这是起始码:

function factorialize(num) {
return num;
}

factorialize(5);

我不是在寻找这个问题的直接答案,但我真的很想知道如何开始。感谢您提前提供任何帮助!

I'm not looking for a direct answer to the question, but I just really want to know how to start. Thanks for any help in advance!

推荐答案

有两种方法可以做到这一点。第一个在循环中,第二个在递归函数中。

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

循环版本是这样的:

function factorialize(num) {

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

  return answer;
}

递归就是这样。

function factorialize(num) {

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

它们都适用于所有正整数。

Both of them will work with all positive integers.

这篇关于在JavaScript中使用Factthize数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆