Skip to main

Hey . A long time ago in the dark ages (before the age of calculators), a smart math kid named Gauss added up numbers really quickly. We are going to do the same thing but with javascript. This is mainly so I can see what embedding examples in a blog looks like. Let’s go !

Here is how we add up 1 to 100: \(\frac{n(n+1)}{2}\). Now this is pretty easy to code into JS:

var number;
var sum = number(number+1)/2;

But what if we wanted to add up numbers beyond 100 and starting at any point? How do we account for negative numbers?

Let’s just think first about adding the sum from one positive number to another positive number:

$$
\frac{a(a+1)}{2}-\frac{b(b+1)}{2}+b
$$

Here a and b are positive integers. Also A is bigger than b. We can see what we are doing is subtracting the sum of 0 to b from the sum of 0 to a. Let’s say you wanted to know the sum of numbers from 3 to 4. First we calculate the larger number (4). Following PEMDAS, 4+1 is 5. 4x4 is 20. 20/2 is 10. Hold the 10. Now we move to the smaller number, 3+1 is 4. 4x3 is 12. 12/2 is 6. Let’s bring back the 10. 10-6 is 4. And the last part of the equation, 4+3 is 7.

Try out that equation with a negative number and see what happens. It will not return the right answer. Let’s correct for this.

$$
\frac{b(b+1)}{2}-\frac{a(a+1)}{2}+a
$$

We now have two equations

$$
\displaylines{\frac{a(a+1)}{2}-\frac{b(b+1)}{2}+b \\ \frac{b(b+1)}{2}-\frac{a(a+1)}{2}+a}
$$

These two equations account for situations where your first number could be greater than your second number. Before coding it in JS, let’s write it using psudo code:

if(the first number is greater than the second number){
$$
\frac{a(a+1)}{2}-\frac{b(b+1)}{2}+b
$$
}
else {
$$
\frac{b(b+1)}{2}-\frac{a(a+1)}{2}+a
$$
}

Coding this equation is merely a matter of translating the math into JS

   function myFunction(){
const a = Math.floor(document.getElementById("number1").value);
const b = Math.floor(document.getElementById("number2").value);
const answer1 = (a*(a+1)/2)-(b*(b+1)/2)+b;
const answer2 = (b*(b+1)/2)-(a*(a+1)/2)+a;
if(a>b){
document.getElementById("demo").innerHTML = answer1;
}
else {
document.getElementById("demo").innerHTML = answer2;
}
}

Math floor is used because we are converting an input given by the user from a string to a number. Later on with document.getElementById("demo").innerHTML = answer1; we are putting the result into the html. This is not the relevant to the post and that is why the HTML is not displayed but it is a point of clarifacation. Below you can try the widget yourself to see the sum of numbers from 1 to 100. Play around and change the values to any whole number you’d like.

Type in a number

Type in another number