How to Compute a Cube as Sums in Golang


The challenge

You will be given a number n (where n >= 1) and your task is to find n consecutive odd numbers whose sum is exactly the cube of n.

**Mathematically:
** cube = n ** 3
sum = a1 + a2 + a3 + ….. + an
sum == cube
a2 == a1 + 2, a3 == a2 + 2, …….

For example:

FindSummands(3) == []int{7,9,11}
// ..because 7 + 9 + 11 = 27, the cube of 3.
// Note that there are only n = 3 elements in the array.

Write function findSummands(n) which will return an array of n consecutive odd numbers with the sum equal to the cube of n (n*n*n).

The solution in Golang

Option 1:

package solution
func FindSummands(n int) []int {
    res := []int{}
    y := n * n - n + 1
    for i := 0; i<n; i++ {
      res = append(res, y + 2 * i)
    }
    return res
}

Option 2:

package solution
func FindSummands(n int) []int {
  a := n*n - n + 1
  res := make([]int, n)
  for i := 0; i < n; i++ {
    res[i] = a + i*2
  }
  return res
}

Option 3:

package solution
func FindSummands(n int) []int {
  a:=n*n-n+1; arr:=make([]int, n)
  for i:=0; i<n; i++ { arr[i] = a; a+=2 }
  return arr
}

Test cases to validate our solution

package solution_test

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

var _ = Describe("Example Tests: 1 through 4",func() {
    test_sols := [...][]int{
        []int{1},
        []int{3,5},
        []int{7,9,11},
        []int{13,15,17,19},
    }
    for i,v := range []int{1,2,3,4} {
        It(fmt.Sprintf("test for number %d",v),func() {
            num := FindSummands(v)
            Expect(num).To(Equal(test_sols[i]))})
    }
})