我怎样才能得到从 1 到给定数字的所有数字相加的倒数?

How can I get the inverse of adding up all the numbers in from 1 to a given number?

我不太确定如何问这个问题。我将尝试解释我要做什么:

首先,我会将 1 中的所有数字(它总是 1)相加到一个范围内,比如 10:

let input = 10
let out = 0

while (input > 0) {
  out += input--
}

// 10 + 9 + 8 .... + 2 + 1 = 55
console.log(out)

我想做的是从输出 55 返回输入数字 10。即

const out = addRange(10) // 55
inverseRange(out) // 10

我觉得可能有一个简单的公式可以得到这个,但我似乎无法弄清楚。我已经尝试过试错解决方案,但无济于事,我觉得这也是一个糟糕的解决方案。

感谢任何帮助、建议或改进。谢谢。

首先,您可以将 addRange 函数简化为 Carl Gauss' formula(first+last)*(last/2),这可以简化为这个,因为您始终从 1:[=25 开始工作=]

(x ** 2 + x) / 2

您可以使用高度简化的二次公式来获取唯一的正值(因为您永远不会有负值):

const addRange = x => (x ** 2 + x) / 2
const inverse = x => Math.sqrt(1 + 8 * x) / 2 - 0.5

console.log(addRange(10))
console.log(inverse(55))

解释:

First, lets break down Gauss' formula. We already know that when x = 10, the output is 55, so lets write that, and try to solve for x:

(x + 1) / 2 * x = 55    
(x + 1) / 2 = 55 / x    // divide by x
x + 1 = 110 / x         // multiply by 2
x = 110 / x - 1         // minus 1
x^2 = 110 - x           // multiply by x
x^2 + x = 110           // add x
x^2 + x - 110 = 0       // minus 55

Now we are left with a quadratic equation. We can use the quadratic formula to find x:

First, lets write that into JS:

(-1 * b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a)

We can substitute out a and b for 1, these will never change in our equation, and since it is negative 30, we can invert the minus before 4ac:

(-1 * 1 + Math.sqrt(Math.pow(1, 2) + (4 * 1 * c))) / (2 * 1)

which simplifies to

(-1 + Math.sqrt(1 + (4 * c))) / 2
// or
Math.sqrt(1 + (4 * c)) / 2 - 0.5

Note however, in our equation, our 55 was doubled to 110, so we should do the same inside our formula (4 -> 8):

Math.sqrt(1 + (8 * c)) / 2 - 0.5