Monday, February 27, 2023
HomeSoftware EngineeringThe right way to Clear up Easy Sq. Numbers in Golang

# The right way to Clear up Easy Sq. Numbers in Golang

## The problem#

On this problem, you’ll be given a quantity `n` (`n > 0`) and your job can be to return the smallest sq. quantity `N` (`N > 0`) such that `n + N` can be an ideal sq.. If there is no such thing as a reply, return `-1` (`nil` in Clojure, `Nothing` in Haskell, `None` in Rust).

``````resolve 13 = 36
<em>; as a result of 36 is the smallest excellent sq. that may be added to 13 to kind an ideal sq. => 13 + 36 = 49</em>

resolve 3 = 1 <em>; 3 + 1 = 4, an ideal sq.</em>
resolve 12 = 4 <em>; 12 + 4 = 16, an ideal sq.</em>
resolve 9 = 16
resolve 4 = nil
``````

## The answer in Golang#

Choice 1:

``````bundle answer
func Clear up(n int) int {
res := -1
for i:= 1; i * i < n; i++ {
if n % i == 0 && (n / i - i) % 2 == 0 {
res = (n / i - i) *  (n / i - i) / 4
}
}
return res
}
``````

Choice 2:

``````bundle answer
import "math"
func Clear up(n int) int {
// n+a**2==b**2 => n=b2-a2=(a-b)(a+b) => b=(c+d)/2; a=d-b
for i := int(math.Sqrt(float64(n))); i > 0; i-- {
if npercenti == 0 {
c, d := i, n/i
b := (c + d) / 2
a := d - b
if a > 0 && n+a*a == b*b { return a * a }
}
}
return -1
}
``````

Choice 3:

``````bundle answer
import "math"
func Clear up(n int) int {
upperBound := n
lowerBound := 1
for  lowerBound <= upperBound {
sq. := lowerBound*lowerBound
numToCheck := math.Sqrt(float64(sq. + n))
if math.Ground(numToCheck) == math.Ceil(numToCheck) {
return sq.
}
lowerBound++
}
return -1
}
``````

## Take a look at instances to validate our answer#

``````bundle solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Instance exams", func() {
It("It ought to work for fundamental exams", func() {
Count on(Clear up(1)).To(Equal(-1))
Count on(Clear up(2)).To(Equal(-1))
Count on(Clear up(3)).To(Equal(1))
Count on(Clear up(4)).To(Equal(-1))
Count on(Clear up(5)).To(Equal(4))
Count on(Clear up(7)).To(Equal(9))
Count on(Clear up(8)).To(Equal(1))
Count on(Clear up(9)).To(Equal(16))
Count on(Clear up(10)).To(Equal(-1))
Count on(Clear up(11)).To(Equal(25))
Count on(Clear up(13)).To(Equal(36))
Count on(Clear up(17)).To(Equal(64))
Count on(Clear up(88901)).To(Equal(5428900))
Count on(Clear up(290101)).To(Equal(429235524))
})
})
``````
RELATED ARTICLES