The 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 sum of the numbers within the nth row of this triangle (beginning at index 1) e.g.: (Enter –> Output)
1 --> 1
2 --> 3 + 5 = 8
The answer in Golang
Choice 1:
bundle resolution
func RowSumOddNumbers(n int) int {
return n * n * n
}
Choice 2:
bundle resolution
import "math"
func RowSumOddNumbers(n int) int {
return int(math.Pow(float64(n), 3))
}
Choice 3:
bundle resolution
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
}
Check instances to validate our resolution
bundle solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Fastened assessments", func() {
It("Testing for 1", func() { Count on(RowSumOddNumbers(1)).To(Equal(1)) })
It("Testing for two", func() { Count on(RowSumOddNumbers(2)).To(Equal(8)) })
It("Testing for 13", func() { Count on(RowSumOddNumbers(13)).To(Equal(2197)) })
It("Testing for 19", func() { Count on(RowSumOddNumbers(19)).To(Equal(6859)) })
It("Testing for 41", func() { Count on(RowSumOddNumbers(41)).To(Equal(68921)) })
It("Testing for 42", func() { Count on(RowSumOddNumbers(42)).To(Equal(74088)) })
It("Testing for 74", func() { Count on(RowSumOddNumbers(74)).To(Equal(405224)) })
It("Testing for 86", func() { Count on(RowSumOddNumbers(86)).To(Equal(636056)) })
It("Testing for 93", func() { Count on(RowSumOddNumbers(93)).To(Equal(804357)) })
It("Testing for 101", func() { Count on(RowSumOddNumbers(101)).To(Equal(1030301)) })
})