从n到m的偶数和,无论n <m或=“” n =“”> m

时间:2019-05-20 19:58:48

标签: javascript html

我试图计算从nm的数字总和,而不管n>m还是n<m。我只设法在n<m期间使它工作。 有人可以帮我吗?

       function SumEvenN()
{
    var n = getFirstNumber();
    var m = getSecondNumber();

    var s = 0;

    if (n<m)
    {
        min = n;
        max = m;
    }
    else if (m<n)
    {
        min = m;
        max = n;
    }

    if (n>m)
    {
        [n, m] = [m, n]
    }
    for (var i = 2; i<=m; i++)
    {
        if (i % 2 == 0)
        {
            s += i;
        }
    }
    alert(s);

}


function getFirstNumber()
{
    var a = document.getElementById("first-number");    
    return parseInt(a.value);
}

function getSecondNumber()
{
    var b = document.getElementById("second-number");   
    return parseInt(b.value);
}

3 个答案:

答案 0 :(得分:3)

尝试

function SumEvenN(n,m) {
  if(n>m) [n, m] = [m, n];  // swap variables if n>m
  n=n%2 ? n+1 : n;          // if n is odd add 1 to it
  m=m%2 ? m-1 : m;          // if m is odd add -1 to it
  let t=(m-n+2)/2;          // number of even elements between n and m
  return t*(n+m)/2;         // use formula of arithmetic progression sum
}

function SumEvenN(n,m) {
  if(n>m) [n, m] = [m, n];  // swap variables if n>m
  n=n%2 ? n+1 : n;          // if n is odd add 1 to it
  m=m%2 ? m-1 : m;          // if m is odd add -1 to it
  let t=(m-n+2)/2;          // number of even elements between n and m
  return t*(n+m)/2;         // use foruma of arithmetic progression sum
}

function calc() {
  console.log(SumEvenN(+first.value, +second.value) );
}
<input id="first" type="number" value="9"/>
<input id="second" type="number" value="16"/>
<button id="btn" onclick="calc()">Calc</button>

答案 1 :(得分:2)

您可以使用Math.minMath.max来获取最小值和最大值。

然后使用第一个偶数从最小值到最大值进行单次循环,并迭代直到该值大于最大值。

将值添加到总和。

function sumEven(a, b) {
    var min = Math.min(a, b),
        max = Math.max(a, b),
        value,
        sum = 0;
        
    for (value = min + min % 2; value <= max; value += 2) {
        sum += value;
    }
    
    return sum;
}

console.log(sumEven(1, 5)); //  6
console.log(sumEven(5, 1)); //  6
console.log(sumEven(2, 8)); // 20
console.log(sumEven(8, 2)); // 20

答案 2 :(得分:1)

尽管这可能是一个简单得多的数学方程式,但您的问题是此行:

for (var i = 2; i<=m; i++)

请使用上面找到的最小值和最大值:

for (var i = min; i <= max; i++)

const getFirstNumber = () => 9;
const getSecondNumber = () => 4;

function SumEvenN() {
  var n = getFirstNumber();
  var m = getSecondNumber();

  var s = 0;

  if (n<m)
  {
      min = n;
      max = m;
  }
  else if (m<n)
  {
      min = m;
      max = n;
  }
  for (var i = min; i <= max; i++)
  {
      if (i % 2 == 0)
      {
          s += i;
      }
  }
  alert(s);

}

SumEvenN();