Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a function that returns the factorial of each integer in an array

I'm new to coding and have been given this question that I cannot seem to get right:

Create a function that takes an array of positive integers and returns an array of the factorials of these numbers.

  E.g. [4, 3, 2] => [24, 6, 2]

The factorial of a number is the product of that number and all the integers below it.

  E.g. the factorial of 4 is 4 * 3 * 2 * 1 = 24

If the number is less than 0, reject it.

The code that I have created is this;

function getFactorials(nums) {
   if (nums === 0 || nums === 1)
      return 1;
   for (var i = nums - 1; i >= 1; i--) {
      nums *= i;
   }
   return nums;
} 

The code is being run against this test;

describe("getFactorials", () => {
  it("returns [] when passed []", () => {
    expect(getFactorials([])).to.eql([]);
  });
  it("returns one factorial", () => {
    expect(getFactorials([3])).to.eql([6]);
  });
  it("returns multiple factorials", () => {
    expect(getFactorials([3, 4, 5])).to.eql([6, 24, 120]);
  });
  it("returns largest factorials", () => {
    expect(getFactorials([3, 8, 9, 10])).to.eql([6, 40320, 362880, 3628800]);
  });
});

How should I do this?

like image 686
Geo Avatar asked Nov 16 '25 16:11

Geo


1 Answers

First off, make a recursive function that calculates the factorial of a single number:

function factorial(num) {
    if (num == 0 || num == 1) {
        return 1;
    }
    return num * factorial(num - 1);
}

Then to do it for an array, just use Array.prototype.map() like so:

function getFactorials(arr) {
    var result = arr.map(x => factorial(x));
    return result;
}

Here's a demonstration:

 

function factorial(num) {
    if (num == 0 || num == 1) {
        return 1;
    }
    return num * factorial(num - 1);
}

function getFactorials(arr) {
    var result = arr.map(x => factorial(x));
    return result;
}

console.log(getFactorials([4, 8, 10])); 
console.log(getFactorials([]));
console.log(getFactorials([1, 2, 3, 4, 5]));

Hopefully this helps!

like image 100
Jack Bashford Avatar answered Nov 19 '25 04:11

Jack Bashford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!