simplifying the mathematical solution for Sum All Numbers in a Range (#35007)
* simplifying the mathematical solution We don't need to sort the two number array, using Math.abs() we can get the count of the numbers in range and calculate the sum. * Remove previously relevant info regarding sort() * Clarify code for better readability * change let to const according to review * added missing semicolon
This commit is contained in:
committed by
The Coding Aviator
parent
6f5610c4f3
commit
5dd27f88e4
@ -63,29 +63,28 @@ Since the numbers might not be always in order, using `max()` and `min()` will h
|
||||
|
||||
##  Intermediate Code Solution:
|
||||
|
||||
function sumAll(arr) {
|
||||
const sumAll = (arr) => {
|
||||
// Buckle up everything to one!
|
||||
|
||||
// Using ES6 arrow function (one-liner)
|
||||
var sortedArr = arr.sort((a,b) => a-b);
|
||||
var firstNum = arr[0];
|
||||
var lastNum = arr[1];
|
||||
const startNum = arr[0];
|
||||
const endNum = arr[1];
|
||||
|
||||
// Get the count of numbers between the two numbers by subtracting them and add 1 to the absolute value.
|
||||
// ex. There are |1-4| + 1 = 4, (1, 2, 3, 4), 4 numbers between 1 and 4.
|
||||
const numCount = Math.abs(startNum - endNum) + 1
|
||||
|
||||
// Using Arithmetic Progression summing formula
|
||||
|
||||
var sum = (lastNum - firstNum + 1) * (firstNum + lastNum) / 2;
|
||||
const sum = (startNum + endNum) * numCount / 2;
|
||||
return sum;
|
||||
}
|
||||
};
|
||||
|
||||
 <a href='https://repl.it/CLm7/0' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
### Code Explanation:
|
||||
|
||||
* Firstly, we create a variable called `sortedArr` which sorts it from the lowest to the highest value.
|
||||
* `firstNum` is equal to the first number and `lastNum` is equal to the second number.
|
||||
* Next, using the Arithmetic Progression summing formula we let `sum` equal `(lastNum - firstNum + 1) * (firstNum + lastNum) / 2`.
|
||||
* Finally, we return `sum`.
|
||||
|
||||
The line `var sortedArr = arr.sort((a,b) => a-b);` is probably what will have you more confused. This would be the same as creating a function that returns `a-b` for the `sort()` which is the standard way to sort numbers from smallest to largest. Instead using arrow or fat arrow function, we are able to do all that in one single line thus allowing us to write less.
|
||||
* The formula for calculating the sum of a continuous range is "(startNum + endNum) * numCount / 2".
|
||||
* arr[0] and arr[1] can either be startNum or endNum, order doesn't matter.
|
||||
* We can get the count of numbers in range by "Math.abs(arr[0] - arr[1]) + 1".
|
||||
* Applying the formula by plugging in the numbers.
|
||||
|
||||
#### Relevant Links
|
||||
|
||||
|
Reference in New Issue
Block a user