Home > Net >  What's the formula for the sum of integers between n and m?
What's the formula for the sum of integers between n and m?

Time:08-02

I am looking at this challenge:

The formula to compute the sum from 1 to n is:

      total = n * (n 1) / 2

Write a function that computes the sum of all values between n and m, inclusive.

Is there some way to use that formula, n, and m to get the answer? Think outside the box... You don't have to come up with a new formula; there's a way to use the existing one to solve it.

I still passed all of the tests by writing this code:

function solution(n, m){
    let numsArr = [];
    for(i=n; i <= m; i  ){
        numsArr.push(i);
    }
    let initialValue = 0;
    let sum = numsArr.reduce(
        (previousValue, currentValue) => previousValue   currentValue,
        initialValue
    );
    return sum
}

console.log(solution(5,9));

But how do I solve it using the specified formula?

CodePudding user response:

The formula you want is the difference between sum up to m minus sum up to n-1.

const sum = (a) => a * (a   1) / 2;

const mySum = (m, n) => sum(m) - sum(n - 1);

console.log(mySum(9, 5));

CodePudding user response:

The result is ((m - n) / 2 n) * (m - n 1).

First get the average between m and n: ((m - n) / 2 n).

Then multiply it by the numbers count: (m - n 1).

const average = ((m - n) / 2   n)
const numbersCount = (m - n   1)
const result = average * numbersCount
  • Related