[英]Return array with factorial number from another array
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;
}
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));
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])
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 ]
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);
function getFactorials(nums) { const factNums = nums.map( function factorial (num) { return (num == 0 ? 1 : num * factorial(num -1)); } ) return factNums; }
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.