# 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:

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```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.```Code language: JavaScript (javascript)```

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
}
```Code language: Go (go)```

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
}
```Code language: Go (go)```

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
}
```Code language: Go (go)```

## 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]))})
}
})
```Code language: Go (go)```
Tags:
Subscribe
Notify of