loading...
Cover image for Code Kata: Calculate the sum of consecutive odd numbers

Code Kata: Calculate the sum of consecutive odd numbers

khwilo profile image Khwilo Kabaka ・2 min read

Problem

Given the triangle of consecutive odd numbers:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...

Calculate the row sums of this triangle from the row index (starting at index 1)

Before looking at the solution, try solving the problem by yourself first.

Solution

In order to solve the above problem, we need to look at common patterns that the above triangle produces. The first one that I arrived at is the first value of each row follows a particular pattern. To get the first value of a particular row, we multiply the row by itself, then we subtract the result of removing the value 1 from the row. If n is the row then to get the starting number we will use the following expression (n * n) - (n - 1). From this formulae, we can get the odd numbers that are in a particular row by looping n times and adding the values to an array data structure. We get the odd number by adding 2 to the current starting number value. The array data structure is used here to store the values and calculate the resultant sum.

Alt Text

Refactoring the code

The above code logic can be reduced to one line. If you look keenly, the sum of the values in each row results in finding the cube of the particular row. The logic will resemble this:

Alt Text

That is all for the challenge. If you have any questions or suggestions, feel free to ask.

Discussion

pic
Editor guide