CodeWars - Sum of odd Numbers - For loop

Viewed 13869

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.

6 Answers

for javascript this would be simply

Math.pow(n,3)
int rowSumOddNumbers(int n) {
  var odd = [];
  var starts = (n * n) - (n - 1);

  while(n > 0){
    odd.add(starts);
    starts += 2;
    n--;
  }

  int sum = odd.reduce((value, element) => value + element);
  print(sum);
  return sum;
}

For PHP:

function rowSumOddNumbers($n) {
  return pow($n, 3);
}
Related