Sunday, April 14, 2024
HomeSoftware EngineeringMethods to Compute a Dice as Sums in Golang

# Methods to Compute a Dice as Sums in Golang

## The problem#

You’ll be given a quantity `n` (the place `n >= 1`) and your activity is to search out `n` consecutive odd numbers whose sum is strictly the dice of `n`.

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

For instance:

``````FindSummands(3) == []int{7,9,11}
// ..as a result of 7 + 9 + 11 = 27, the dice of three.
// Word that there are solely n = 3 parts within the array.
``````

Write operate `findSummands(n)` which can return an array of n consecutive odd numbers with the sum equal to the dice of n `(n*n*n)`.

Choice 1:

``````package deal resolution
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
}
``````

Choice 2:

``````package deal resolution
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
}
``````

Choice 3:

``````package deal resolution
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
}
``````

## Take a look at circumstances to validate our resolution#

``````package deal solution_test

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

var _ = Describe("Instance Assessments: 1 via 4",func() {
test_sols := [...][]int{
[]int{1},
[]int{3,5},
[]int{7,9,11},
[]int{13,15,17,19},
}
for i,v := vary []int{1,2,3,4} {
It(fmt.Sprintf("check for quantity %d",v),func() {
num := FindSummands(v)
Count on(num).To(Equal(test_sols[i]))})
}
})
``````
RELATED ARTICLES