Software Engineering

Irreducible Sum of Rationals in Golang

Irreducible Sum of Rationals in Golang
Written by admin


The problem

You’ll have a listing of rationals within the type:

lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ]

the place all numbers are constructive integers. It’s important to produce their sum N / D in an irreducible type: which means N and D have solely 1 as a standard divisor.

Return the outcome within the type: "N/D"

If the result’s an integer (D evenly divides N) return: "n"

If the enter record is empty, return: "0"

Examples:

[ [1, 2], [1, 3], [1, 4] ]  -->  [13, 12]
1/2  +  1/3  +  1/4     =      13/12

The answer in Golang

Choice 1:

bundle answer
import"fmt"
func SumFracts(arr[][]int) string {
  a,b:= 0,1
  for _,v:=vary arr{
    c,d:=v[0],v[1]
    okay:=gcd(b,d)
    a,b=(a*d+b*c)/okay,b*d/okay
  }
  okay:=gcd(a,b)
  a,b=a/okay,b/okay
  if b==1 {return fmt.Sprintf("%d",a)}
  return fmt.Sprintf("%d/%d",a,b)
}
func gcd(a, b int) int {
  for b != 0 {
    a, b = b, apercentb
  }
  return a
}

Choice 2:

bundle answer
import "math/massive"
func SumFracts(arr [][]int) string {
  outcome := new(massive.Rat).SetFloat64(0)
  for _, v := vary(arr) {
    rat := massive.NewRat(int64(v[0]), int64(v[1]))
    outcome.Add(outcome, rat)
  }
  return outcome.RatString()
}

Choice 3:

bundle answer
import "math/massive"
func SumFracts(arr [][]int) string {
  sum := massive.NewRat(0,1)
  for _, f := vary arr {
    sum.Add(sum, massive.NewRat(int64(f[0]), int64(f[1])))
  }
  if sum.Denom().Cmp(massive.NewInt(1)) == 0 {
    return sum.Num().String()
  }
  return sum.String()
}

Check instances to validate our answer

bundle solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
func dotest(arr [][]int, exp string) {
    var ans = SumFracts(arr)
    Count on(ans).To(Equal(exp))
}
var _ = Describe("Exams SumFracts", func() {
    It("ought to deal with fundamental instances", func() {
        dotest([][]int{{1, 2}, {1, 3}, {1, 4}}, "13/12")
        dotest([][]int{{1, 3}, {5, 3}}, "2")
    })      
})

About the author

admin

Leave a Comment