- You need to create a program that will take an array of two numbers who are not necessarily in order, and then add not just those numbers but any numbers in between. For example, [3,1] will be the same as
1+2+3and not just3+1
- Use
Math.max()to find the maximum value of two numbers.
- Use
Math.min()to find the minimum value of two numbers.
- Remember to that you must add all the numbers in between so this would require a way to get those numbers.
Solution ahead!
function sumAll(arr) {
var max = Math.max(arr[0], arr[1]);
var min = Math.min(arr[0], arr[1]);
var temp = 0;
for (var i=min; i <= max; i++){
temp += i;
}
return(temp);
}
sumAll([1, 4]);- First create a variable to store the max number between two.
- The same as before for the Smallest number.
- We create a temporary variable to add the numbers.
Since the numbers might not be always in order, using max() and min() will help organize.
function 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];
// Using Arithmetic Progression summing formula
// https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
var sum = (lastNum - firstNum + 1) * (firstNum + lastNum) / 2;
return sum;
}If you found this page useful, you can give thanks by copying and pasting this on the main chat: thanks @Rafase282 @abhisekp
NOTE: Please add your username only if you have added any relevant main contents to the wiki page. (Please don't remove any existing usernames.)