How to Calculate the Sum of the Numbers in the Nth row of a Triangle in Golang

  • Home /
  • Blog Posts /
  • How to Calculate the Sum of the Numbers in the Nth row of a Triangle in Golang

The challenge

Given the triangle of consecutive odd numbers:

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

Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input –> Output)

1 -->  1
2 --> 3 + 5 = 8

The solution in Golang

Option 1:

package solution

func RowSumOddNumbers(n int) int {
    return n * n * n
}

Option 2:

package solution

import "math"

func RowSumOddNumbers(n int) int {
    return int(math.Pow(float64(n), 3))
}

Option 3:

package solution

func RowSumOddNumbers(n int) int {
  res := 0
  for i := (n - 1) * n + 1; i < n * (n + 1); i = i + 2 {
    res = res + i
  }
  return res
}

Test cases to validate our solution

package solution_test

import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)

var _ = Describe("Fixed tests", func() {
    It("Testing for 1", func() { Expect(RowSumOddNumbers(1)).To(Equal(1)) })
    It("Testing for 2", func() { Expect(RowSumOddNumbers(2)).To(Equal(8)) })
    It("Testing for 13", func() { Expect(RowSumOddNumbers(13)).To(Equal(2197)) })
    It("Testing for 19", func() { Expect(RowSumOddNumbers(19)).To(Equal(6859)) })
    It("Testing for 41", func() { Expect(RowSumOddNumbers(41)).To(Equal(68921)) })
    It("Testing for 42", func() { Expect(RowSumOddNumbers(42)).To(Equal(74088)) })
    It("Testing for 74", func() { Expect(RowSumOddNumbers(74)).To(Equal(405224)) })
    It("Testing for 86", func() { Expect(RowSumOddNumbers(86)).To(Equal(636056)) })
    It("Testing for 93", func() { Expect(RowSumOddNumbers(93)).To(Equal(804357)) })
    It("Testing for 101", func() { Expect(RowSumOddNumbers(101)).To(Equal(1030301)) })
})