简体   繁体   English

"Js函数顶部计算阶乘不起作用"

[英]Js function top calculate factorial not working

I was doing this challenge from coderbyte where you have to make a function that calculate the factorial of a given number, this is my not so working solution.我是从 coderbyte 做这个挑战的,你必须创建一个函数来计算给定数字的阶乘,这是我不太可行的解决方案。

function firstFactorial(num) { 

  for (var i = num; i == 1; i--) {
      num = num * i;
  }
  return num;     
}

It just returns whatever number i pass in as an argument, and i'm trying to understand what's wrong.它只是返回我作为参数传入的任何数字,我试图了解出了什么问题。 Is it something to do with the loop or is it something with the variable scope ?它与循环有关还是与变量范围有关?

  1. i == 1 is wired in loop condition it will always be false for all number except 1.So it will always return the same number as result. i == 1处于循环状态,对于除1以外的所有数字都将始终为false,因此它将始终返回与结果相同的数字。

  2. i = num should be i = num-1 to get correct factorial. i = num应该为i = num-1才能获得正确的阶乘。

 function FirstFactorial(num) { for(var i = num-1; i >= 1; i--){ num = num * i; } return num; } console.log( FirstFactorial(5)) 

Your for loop was a bit messed up. 您的for循环有点混乱。 Now it should work. 现在应该可以了。

  function factorial(num){ for(var i = num - 1; i > 0; i--){ num *= i; } return num; } console.log(factorial(5)); 

Your problem is that you have a loop condition i == 1 . 您的问题是您有一个循环条件i == 1 For factorials, it should be i >= 1 , or i > 1 depending on what algorithm you use. 对于阶乘,它应为i >= 1i > 1具体取决于您使用的算法。 My take on a factorial function would be: 我对阶乘函数的看法是:

function calculate(factorial) {
    var newFactorial = factorial;
    while (factorial > 1) {
        factorial--;
        newFactorial *= factorial;
    }
    return newFactorial;
}

 function firstFactorial(num) { const output = eval(Array.from({length: num}, (_, index) => (index + 1)).reverse().join("*")); return output; } console.log(firstFactorial(8));

Rather than iterating through all the numbers using for loop or recursion .而不是使用for loop 或recursion遍历所有数字。 I used built-in Javascript functions.我使用了内置的 Javascript 函数。 I first created an array of length 1-N using Array.from Then, I reversed that array and joined it with * .我首先使用Array.from创建了一个长度为1-N的数组,然后,我反转了该数组并用*加入了它。 Then, I used the eval function to get evaluate the expression.然后,我使用eval函数来评估表达式。 You can also shrink it down to just one line.您也可以将其缩小到仅一行。 So the code will be: const findFactorial = num => eval(Array.from({length: num}, (_, index) => (index + 1)).reverse().join("*")所以代码将是: const findFactorial = num => eval(Array.from({length: num}, (_, index) => (index + 1)).reverse().join("*")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM