【One topic per day】Sum of odd numbers

前端题库,Javascript题集

Posted by Jerry on April 6, 2019

Sum of odd numbers

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) e.g.:

rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8

reply

//method 1:
function rowSumOddNumbers(n) {
  return Math.pow(n, 3);
}

//method 2:
function rowSumOddNumbers(n) {
  let index = (n-1)*n/2,sum=0;
  for(let i=1;i<=n;i++){
    sum += 2*(index+i) - 1
  }
  return sum;
}

同Github,欢迎star