最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

factorial - Factorize function javascript - Stack Overflow

programmeradmin1浏览0评论

I am having a little issue writing a function that factorizes numbers. The hard part is done. However I cannot seem to tell the function to return 1 when num is 0.

PS: which other ways would you write the same function in JavaScript?

var arrOfNum = [];

function factorialize(num) {

  for(i = 1; i <= num; i++){
    // push all numbers to array 
    arrOfNum.push(i);
  }

  // multiply each element of array
  var result = arrOfNum.reduce(function(a,b){
    return a * b;
  });

  console.log(result);
}

I am having a little issue writing a function that factorizes numbers. The hard part is done. However I cannot seem to tell the function to return 1 when num is 0.

PS: which other ways would you write the same function in JavaScript?

var arrOfNum = [];

function factorialize(num) {

  for(i = 1; i <= num; i++){
    // push all numbers to array 
    arrOfNum.push(i);
  }

  // multiply each element of array
  var result = arrOfNum.reduce(function(a,b){
    return a * b;
  });

  console.log(result);
}
Share Improve this question edited Mar 25, 2016 at 12:20 user663031 asked Mar 25, 2016 at 12:08 DrewDrew 1113 silver badges10 bronze badges 2
  • 2 It looks like you're confusing "factorials" and "factorization". – georg Commented Mar 25, 2016 at 12:15
  • check stackoverflow./questions/3959211/… also for a discussion on js factorial impl – Jerome WAGNER Commented Mar 25, 2016 at 12:17
Add a ment  | 

8 Answers 8

Reset to default 3

You already have a for loop, in which you can calculate the factorial at once, without array and reduce.

function factorial(num) {
  var result = 1;
  for(i = 2; i <= num; i++) {
      result *= i;
  }
  return result;
}

You can use the following method that uses the recursion:

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

Roundup:

  • Declaration of local variable i is missing

    var i;
    
  • Declaration of other used variables are over the function distributed. A better way is to declare the variables at top of the function.

  • Array#reduce needs for this task an initialValue as the second parameter.

    The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.

function factorial(num) {
    var i,
        arrOfNum = [],
        result;

    for (i = 1; i <= num; i++) {
        // push all numbers to array 
        arrOfNum.push(i);
    }

    // multiply each element of array
    result = arrOfNum.reduce(function (a, b) {
        return a * b;
    }, 1);

    document.write(num+'! = '+result + '<br>');
}
factorial(0);
factorial(1);
factorial(2);
factorial(5);
factorial(8);

Simply return the value 1

 function factorialize(num) {
       if (num < 1) return 1; //this line is added

       for(i = 1; i <= num; i++){
         arrOfNum.push(i);
       }
       var result = arrOfNum.reduce(function(a,b){
          return a * b;
       });
        console.log(result);
     }

If you give reduce an initial value of 1, everything will work fine even without an explicit check:

var result = arrOfNum.reduce(function(a,b){
   return a * b;
 }, 1);
  ^^^         // PROVIDE EXPLICIT INITIAL VALUE TO REDUCE
 function factorial(n) {
   return Array.apply(0, Array(n)).reduce(function(x, y, z) {
     return x + x * z; //1+(1*0), 1+(1*1),2+(2*2), 6+(6*3), 24+(24*4), ...
   }, 1);
 }

DEMO

Here's a fairly streamlined function that returns an array of all factors of 'n'

You only need to look at candidates < sqrt(n)

For those of you who don't know the | 0; bit when getting sqrt(n) is a faster equivalent of Math.floor()

As factn is defined after some sanity checking the function will either return undefined or an array which is easy to check with something like if(factors = factorize(n) { success code } sorta structure

There are improvements that can be made to this but they're plex and were beyond the requirements when I wrote it - specifically I used this to calculate CSS sprite sizes from a large image by using factorize on the x + y dimensions of an image then creating a third array of shared factors (which gives you a list of all the possible square sprite sizes).

function factorize(n) {
    n = Number(n);
    if(n) {
        if(n > 1) {
            var sqrtn = Math.sqrt(n) | 0;
            var factn = [1, n];
            var ipos = 0;
            for(i = 2; i <= sqrtn; i++) {
                if((n % i) == 0) {
                    ipos++;
                    if((n / i) !== i) {
                        factn.splice(ipos, 0, i, n / i);
                    } else {
                        factn.splice(ipos, 0, i);
                    }
                }
            }
        }
    }
    return factn;
}

Don't know why there are plicated answers. A very simple answer is:

var i;

function factorialOf(num) {
    //Initially set factorial as number
    var factorial = num;
    
    //A for loop starting with 1 and running the times equal to num
    for (i = 1; i < num; i++) {
        //Set factorial to the number itself * i
        factorial = factorial * i;
    }
    //Return factorial
    return factorial;
}

console.log(factorialOf(5));

发布评论

评论列表(0)

  1. 暂无评论