在 JavaScript 中查找三个所需的连续数字

javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/18 3:56:17

我们需要编写一个 JavaScript 函数,该函数接受一个数字,例如 n,并且我们需要检查是否存在三个连续的自然数(非十进制/浮点数),其和等于 n。

如果存在这样的数字,我们的函数应该返回它们,否则应该返回 false。

示例

其代码为 −

const sum = 54;
const threeConsecutiveSum = sum => {
   if(sum < 6 || sum % 3 !== 0){
      return false;
   }
   // three numbers will be of the form:
   // x + x + 1 + x + 2 = 3 * x + 3
   const residue = sum - 3;
   const num = residue / 3;
   return [num, num+1, num+2];
};
console.log(threeConsecutiveSum(sum));

输出

以下是控制台上的输出 −

[ 17, 18, 19 ]

相关文章


有用资源