Solving Sum of N Numbers
Posted on July 14, 2020
This blog post is going to focus on solving the sum of N numbers. It's a typical question that could pop up in a Junior interview, or potentially in your college work. So the question could be what is the sum of the first 1000 numbers.
Using Loops to solve the problem.
We could solve this using a for loop passing in N into the function. For Example:
This will solve the problem, and the result will be 500500 but it is quite inefficient because as the number gets bigger so does the iteration and memory usage.
Thinking of this problem like a maths problem.
So the problem we are attempting to solve is:
sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + ... n
If we think of it, we are technically just doing:
sum = n + (n-1) + (n-2) + (n-3) + (n-4) + (n-5) ... +1
There is an arithmetic solution for this called Arithmetic progression which is described as a sequence of numbers such that the difference between the consecutive terms is constant.
To break it down, let's look at this very simple example:
This sum can be found quickly by taking the number n of terms being added (here 5), multiplying by the sum of the first and last number in the progression (here 2 + 14 = 16), and dividing by 2:
(n(a1 + a2))/2
Using this we get the same result, and it doesn't matter how big the number is as we aren't iterating, we are directly calculating the solution.
I hope you enjoyed the short tutorial on calculating the sum of n numbers, and I hope it helps when you are prepping for some interviews.
I finished the first part of the nanodegree a few days ago and decided to give an indepth review of what is covered, what you learn and what is completed by the end of it.
When you first start thinking about becoming a developer, one of the things you might hear is you need to be a math(s) wizz. I am here to tell you that a small number of developers need the mathematics outside of algebra.