# freeCodeCamp Challenge Guide: Sum All Numbers in a Range

freeCodeCamp Challenge Guide: Sum All Numbers in a Range
0

# Sum All Numbers in a Range

## Problem Explanation

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+3` and not just `3+1`

## Hints

### Hint 1

Use `Math.max()` to find the maximum value of two numbers.

### Hint 2

Use `Math.min()` to find the minimum value of two numbers.

### Hint 3

Remember to that you must add all the numbers in between so this would require a way to get those numbers.

## Solutions

Solution 1 (Click to Show/Hide)
``````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]);
``````

#### Code Explanation

• 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.

Solution 2 (Click to Show/Hide)
``````const sumAll = arr => {
// Buckle up everything to one!
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
const sum = ((startNum + endNum) * numCount) / 2;
return sum;
};
``````

#### Code Explanation

• 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.

Solution 3 (Click to Show/Hide)
``````function sumAll(arr) {
var sum = 0;
for (var i = Math.min(...arr); i <= Math.max(...arr); i++) {
sum += i;
}
return sum;
}

sumAll([1, 4]);
``````

#### Code Explanation

• Creating a variable sum to store the sum of the elements.
• Starting iteration of the loop from min element of given array and stopping when it reaches the max element.
• Using a spread operator (âŚarr) allows passing the actual array to the function instead of one-by-one elements.

Solution 4 (Click to Show/Hide)

Recursive Solution

``````function sumAll([ first, last ] ) {
const step = first - last < 0 ? 1 : -1;
return first !== last
? first + sumAll([ first + step, last ])
: first;
}
``````
9 Likes

Quick question: why does the challenge include the reduce method to the helpful links when none of the 3 solutions above use it?

15 Likes

I donât see any mention or link for the reduce method.

3 Likes

I have:

You donât?

1 Like

That is the challenge, here are solutions, totally different. If they put reduce as a helpful link then that means it can be used to solve the problem. We just happened to have solutions that donât use it here. These solutions are originally from multiple campers and not an official hard answer to the challenge, you are free to come up with your own solution as long as it works regardless of what you use.

3 Likes

Thank you @Rafase282 and @P1xt for your replies.

@Rafase282: I thought that you were working hand in hand with those designing the hints. Hence my surprise. But I get your point.

@P1xt: I really like your solution but I struggle to understand your code coming after the `return`. Would you mind explaining this line step by step for me?

2 Likes

@samuelpath I made most if not all the hints you will see on the on the wiki, the ones on the main site were not done by me. However, FCC is planing on integrating the hints from the wiki into the challenges themselves in the future.

3 Likes

That would be a great move I think.

By the way, Iâm really impressed by your Javascript mastery, so kudo !

1 Like

I wouldnât call myself a master at JavaScript, there are many areas that i donât know or could improve, not directly being on JS. Regardless, thanks!

2 Likes

AgreedâŚ I spent hours trying use the reduce method, to no avail in combination with a loopâŚ

It should not be there; it was misleadingâŚ

5 Likes

I made a crude code for this challenge https://jsfiddle.net/nfhqrh5y/

It gives all output (1,4 > 10, 4,1 > 10, 5,10 > 45 etc) when checking with fiddle.

However, when i paste this code into FCC challenge wont pass.

Ofc im replacing console.log(m) with return m; when pasting so this might not be the problem.

I am aware there are more elegant solutions but want to know why this one is not passable?

Oh i see. I created function with (value, value) type of argument whereas at FCC script is awaiting for ([value, value]), array kind of argument.

Once I devise function to function sumAll(arr)

var min;
var max;
min = arr[0];
max = arr[1];

challenge passed.
Okay i think ill check other solutions as well nowâŚ

Refactored code to suit Math.max()
https://jsfiddle.net/dvezv801/

I used `.reduce()` in my solution:

``````function sumAll(arr) {
arr = arr.sort((a, b) => a - b);
var count = arr[1] - arr[0] + 1;

return Array

// create empty array of length = 'count'
.apply(null, new Array(count))

// populate with values from input array range
.map((num, ind) => arr[0] + ind)

// sum all the values in the range
.reduce(function (accum, curval) {
return accum + curval;
});
}
``````
1 Like

I used the below after reading about Arithmetic Progression. Interested in anyoneâs thoughts. It ignores the use of any array related work and just sticks to the math aspect of the question.

``````function sumAll (arr) {
const min = Math.min(...arr);
const max = Math.max(...arr);
return (((max - min + 1) * (min + max)) / (2));
}``````
2 Likes

damn man i did this

``````function sumAll(arr) {
var a=[];
var b;
if(arr[0]<arr[1]){
b=arr[0];
for(var i=arr[0];i<arr[1]-1;i++){

a.push(b);
b=++arr[0];

}
}else{
b=arr[1];
for(var j=arr[1];j<(arr[0]-1);j++){
a.push(b);
b=++arr[1];
}
}
arr=a.concat(arr);
var sum = arr.reduce(function(a, b) {
return a + b;
}, 0);
return sum;
}

sumAll([5, 10]);``````

Hey, yeah well Iâve pretty much the same as P1xt already wrote above, which in turn pretty much resembles your code. The solution is pretty elegant. Itâs actually just a transformation of basic arithmetic math (GauĂ). Donât get me wrong, I also spent quite some time until I figured it out. But the more thrilling insight for me is how valuable good old math is when it comes to solving problems with code! So good work!

1 Like
``````function sumAll(arr) {
var sum = 0;
arr[0] > arr[1] && arr.reverse();
for (i = arr[0]; i <= arr[1]; sum += i++);
return sum;
}

sumAll([1, 4]);
``````
2 Likes