Reputation: 972
This function will receive an array of positive integers and it should return a new array with the factorial of each number.
So far I came up with this but it doesn't work and I don't know where is the problem, any ideas?
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
if(nums[i] <= 1) {
return 1;
} else {
arr.push(nums[i] * getFactorials(nums[i] - 1));
}
}
return arr;
}
Upvotes: 0
Views: 3639
Reputation: 1
function getFactorials(nums) {
const factNums = nums.map(
function factorial (num) {
return (num == 0 ? 1 : num * factorial(num -1));
}
)
return factNums;
}
Upvotes: 0
Reputation: 5780
const factorial = (n) => {
let res = [];
while(n != 0){
//get all integers less than or equal to n
res.push(n);
n--;
}
return res.reduce((x, y) => {
return x * y;
//reduce the array of integers into a single number via multiplication
});
}
const nums = [1, 2, 3, 4, 5];
const factorialArr = (arr) => {
return arr.map(n => {
//iterate through a list of numbers and return the factorial of each
return factorial(n);
});
}
const result = factorialArr(nums);
console.log(result) -> // Array [ 1, 2, 6, 24, 120 ]
Upvotes: 1
Reputation: 68923
Try the following:
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
let j, fact;
fact=1;
for(let j=1; j<=nums[i]; j++)
{
fact= fact*j;
}
arr.push(fact);
}
return arr;
}
let res = getFactorials([5,9])
console.log(res);
Upvotes: 2
Reputation: 6311
try this use map
var a = [1, 2, 3, 4, 5];
function fact(x) {
return (x == 0) ? 1 : x * fact(x-1);
}
console.log(a.map(fact));
Upvotes: 6
Reputation: 959
Try this way:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
function getFactorials (nums) {
let arr = [];
for(let i = 0; i < nums.length; i++) {
arr.push(factorial(nums[i]));
}
return arr;
}
getFactorials([6,5,3])
Upvotes: 1
Reputation: 13
#include <stdio.h>
int iFactorial(int iCount)
{
int iProduct = 1;
int iNumber = 1;
while (iNumber <= iCount)
{
iProduct *= iNumber;
iNumber++;
}
return iProduct;
}
int main(void)
{
int iFac[10] = {0};
int iCount = 0;
for (iCount = 0; iCount < 9; iCount++)
iFac[iCount] = iFactorial(iCount);
for (iCount = 0; iCount < 9; iCount++)
printf("\nThe value of the factorial is %d\n", iFac[iCount]);
return 0;
}
Upvotes: -3