Drew
Drew

Reputation: 111

Factorize function javascript

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);
}

Upvotes: 1

Views: 3442

Answers (8)

Paltze
Paltze

Reputation: 87

Don't know why there are complicated 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));

Upvotes: 0

Yassir Irfan
Yassir Irfan

Reputation: 1210

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);
    }
}

Upvotes: 2

peardox
peardox

Reputation: 497

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 complex 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;
}

Upvotes: 0

isvforall
isvforall

Reputation: 8926

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;
}

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386680

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);

Upvotes: 1

Dipali Vasani
Dipali Vasani

Reputation: 2536

 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

Upvotes: 0

user663031
user663031

Reputation:

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

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68413

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);
     }

Upvotes: 0

Related Questions