查找两个数字之间的算术级数

问题描述 投票:0回答:2

我有两个数字,我需要找到这两个数字之间的算术级数,以使它始终包含数字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,则会得到缺少zero[-7, -4.17, -1.33, 1.5, 4.33, 7.17, 10]

以下情况

  1. [numberOfPoints是固定的min,并且max有所不同。
  2. [min始终为负max可以为负,也可以不为负。
  3. A negative threshold value可以加到min上以获得数字为[[zero的算术级数。
javascript algorithm math numbers series
2个回答
0
投票
此任务无法解决

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,则步的最大值必须为1以不超过最大值。

添加负阈值并不重要,因为它只会增加step的值。

PS:在min is always negative max may or may not be negative.以上的示例中,我忽略了此步骤,因为此步骤甚至更容易证明是不可解决的。 min=-10max=-9之间没有零,添加负阈值不会改变它。


0
投票

/* 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 a positive 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 */
© www.soinside.com 2019 - 2024. All rights reserved.