简体   繁体   中英

factorial javascript code?

I wrote this code for a factorial in JS using a for loop but it is not displaying the desired output.

what is wrong with my code?

var solution;
for (x = 12; x > 0; x -= 1) {
    for (y = 12; y > 0; y -= 1){
        solution = y * x; 
    }
} console.log(solution);

You aren't using solution when you redefine it, so basically you are computing

solution = 1 * 1;

Your code seems to have nothing to do with factorial or recursion (which requires a funtion definition)?

A factorial for 12 is 12 * 11 * 10 ... * 2 * 1.

To write that in a loop you would want to multiply the result of the previous iteration by the current one like so.

var solution = 1;
for (x = 12; x > 0; x -= 1) {
  solution = solution*x
} 
console.log(solution);

Your example will end with y and x being 1. Thus outputting 1*1. You need to save the result of the previous operation.

I recommend you follow the community rules for future questions, I don't want to discourage you from this community either, but please google in the future.

Your inner for loop isn't necessary. You need to set an initial condition (ie setting the solution initially being 1) then repeatedly multiply the digits from 12 to 1 to that initial condition.

Using a for loop is known as 'iterative' rather than recursive.

To do it recursively you need to at least define a function. Learning how to think recursively is really something you should google though.

Either way, both ways are pretty rudimentary for finding factorials and it doesn't really matter which you use.

 // Iterative var solution = 1, number = 12, x, y; for (x = number; x > 0; x -= 1) { solution *= x; } console.log(solution); // Recursive function fact(n){ if(n == 1) return 1; else return n * fact(n - 1); } console.log(fact(number))

 var fact = 1; function factorial(n) { for (; n > 1; n--) { fact *= n; } return fact; } console.log(factorial(8));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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