JavaScript 求和数字的递归乘积

javascriptweb developmentobject oriented programming更新于 2025/10/2 19:24:17

我们必须创建一个函数,该函数接受任意数量的参数(数字文字),将它们相加,并在答案只有 1 位数字时返回数字的乘积。

例如 −

如果参数是 −

16、34、42

我们必须先将它们相加 −

16+34+42 = 92

然后继续将数字相乘,直到得到像这样的 1 位数字 −

9*2 = 18
1*8 = 8

当我们得到一位数字时,我们必须从函数中返回它。

我们将把它分成两个函数 −

  • 一个函数接受一个数字并返回其数字的乘积,我们将使用递归来实现,让我们将第一个函数称为 product()。

  • 第二个函数递归调用此 product() 函数并检查乘积是否恰好为 1 位数字,否则它将继续迭代。

整个功能的代码将是 −

示例

const recursiveMuliSum = (...numbers) => {
   const add = (a) => a.length === 1 ? a[0] : a.reduce((acc, val) => acc+val);
   const produce = (n, p = 1) => {
      if(n){
         return produce(Math.floor(n/10), p*(n%10));
      };
      return p;
   };
   const res = produce(add(numbers));
   if(res > 9){
      return recursiveMuliSum(res);
   }
   return res;
};
console.log(recursiveMuliSum(16, 28));
console.log(recursiveMuliSum(16, 28, 44, 76, 11));
console.log(recursiveMuliSum(1, 2, 4, 6, 8));

输出

控制台中的输出将是 −

6
5
2

相关文章


有用资源