查找两个数字之间的等差级数

Find arithmetic progression between two numbers

我有两个数字,我需要找到这两个数字之间的算术级数,它应该始终包含数字 zero

下面是我的代码。

var numberOfPoints = 6;
var min = -5;   
var max = 10;
var step = (max - min) / numberOfPoints;
var pointsArray = [min];
var point = min;
for (var i = 0; i < numberOfPoints; i++) {
   point = point + step;
   pointsArray.push(+point.toFixed(2));
}
console.log(pointsArray); //[-5, -2.5, 0, 2.5, 5, 7.5, 10]

代码运行良好。

但是如果我更改 min = -7,我会得到缺少 [-7, -4.17, -1.33, 1.5, 4.33, 7.17, 10]

情况如下

  1. numberOfPoints 固定 minmax 变化。
  2. min 总是负数 max 可能是也可能不是负数。
  3. A negative threshold value可以和min相加得到等差数列

这个任务无法解决

Following is the situation

- numberOfPoints is fixed min and max varies.
- min is always negative max may or may not be negative.
- A negative threshold value can be added to min to get an arithmetic progression having number zero in it.

证明: numberOfPoints= 6min=-1000max=1,你不能在 6 个步骤中得到 arithmetic progression 零,因为在 6 个步骤中,步骤的最小差异是 1001/6=166.86,而如果你包括 0,step 的最大值必须是 1 才不会超过最大值。

添加负阈值无关紧要,因为它只会增加步长的值。

PS:我在上面的例子中忽略了这一步min is always negative max may or may not be negative.,因为这一步更容易证明无解。 min=-10max=-9,它们之间没有零,添加负阈值不会改变它。

/*

min and max must have opposite signs, because there's no zero between two negative numbers
but they cannot be arbitrary, they have to satisfy a condition

if the k-th term of the progression is zero then min + k * step = 0 or 
min + k * (max - min) / numberOfPoints = 0 
from which k = - numberOfPoints * min / (max - min)
the condition is that - numberOfPoints * min / (max - min) must be an integer 
in the interval [1, numberOfPoints]
otherwise there's no solution

in the first example that you have (-6) * (-5) / (10 - (-5)) = 3
but in the second (-6) * (-7) / (10 - (-7)) = 2.470588235294118
(-4, 2), (-3, 3), (-2, 4) will all work, but (-2, 3) won't

*/