Skip to content
Advertisement

CodeWars – Sum of odd Numbers – For loop

I have attempted to make a piece of code that accepts an input of “n”, calculates the sum of the numbers on the nth line an odd number triangle, which looks like:

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

etc. So for n = 3, the sum would be 7 + 9 + 11 ie 27

I know that n is not only the line number but also equals the number of numbers on that line. so n = 3 also have 3 odd numbers on it. Therefore I thought that I could get the first number of the line, then just loop through adding two to the previous number then sum it.

My code below doesn’t work, so for an input of n=43, my code calculates that the sum is 3570 whereas it actually equals 79507.

public static int rowSumOddNumbers(int n) {
    int firstNum = (2 * n) - 1;
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += (firstNum + 2);
    }
    return total;
}

I believe my problem is that I’m not adding the previous number together with the current number + 2. Should it be that I need to store the previous loop’s outcome than add it to the current loop’s outcome?

Any help appreciated.

Advertisement

Answer

Mathematically, the sum of the nth line of odd numbers is n3, so this gives the correct result:

int rowSumOddNumbers(int n) {
    return n * n * n;
}

I leave the derivation to the reader…

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement