The Gauss Sum: Introduction to sum of n arithmetic numbers using algorithm.

Photo by Jake Givens on Unsplash

The Gauss Sum: Introduction to sum of n arithmetic numbers using algorithm.

ยท

2 min read

So, let's say you have to add an array of numbers from 1 to n. What I usually did before I started learning the algorithm and data structures was to loop over every element of the array and add it to the sum. But after learning about the Gauss Sum, I learned how easy and effective is this. So I thought I should write a simple blog on it. So that It will be a spaced-repetition for me, and also it would be helpful for other folks. So this is a very simple article on it. Let's Learn..

Using for Loop:

function sum(arr){
let sum=0;
for(i=0;i<arr.length;i++){
   sum=sum+i;
    }
}
return sum;

//Output 21 for [1,2,3,4,5,6]

So here what happens is that it iterates through every element in the array, which takes so much time if there are many elements and have a complexity of O(n).
Whenever a new element is added, then it will be added to the complexity of the function. Which creates a Linear Complexity O(n).

Using Gauss Sum:

function sum (arr) {

let n = arr.length-1;

let sum = (n *(n + 1)) / 2 ; 

return sum;
}

So in this function what happens is, it is applying the Gauss Sum so that it doesn't have to iterate through each element rather the function sum just the use the formula (n*(n+1))/2. So by this the complexity is now O(1). Which creates a constant complexity O(1). Even if new elements are added, it doesn't change the complexity as only the last number is selected for this formula.

So, this shows that using algorithms help the ways in which a task can be improved and make them more effective and easier than before. Click here to learn more.

I hope this short and simple blog helps you to learn and understand Gauss Sum. Do try it out yourself and let me know what you think.

Thank You for reading this. More Contents To Come. Stay Tuned!

ย