Skip to content

Instantly share code, notes, and snippets.

@qbig
Created August 15, 2018 16:33
Show Gist options
  • Select an option

  • Save qbig/5c29197192e5b45688f590add240a360 to your computer and use it in GitHub Desktop.

Select an option

Save qbig/5c29197192e5b45688f590add240a360 to your computer and use it in GitHub Desktop.
Working with numeric data types using math and math/big

Working with math

  package math

        import (
         "fmt"
         "math"
        )

        // Examples demonstrates some of the functions
        // in the math package
        func Examples() {
            //sqrt Examples
            i := 25

            // i is an int, so convert
            result := math.Sqrt(float64(i))

            // sqrt of 25 == 5
            fmt.Println(result)

            // ceil rounds up
            result = math.Ceil(9.5)
            fmt.Println(result)

            // floor rounds down
            result = math.Floor(9.5)
            fmt.Println(result)

            // math also stores some consts:
            fmt.Println("Pi:", math.Pi, "E:", math.E)
        }

Working with math/big

        package math

        import "math/big"

        // global to memoize fib
        var memoize map[int]*big.Int

        func init() {
            // initialize the map
            memoize = make(map[int]*big.Int)
        }

        // Fib prints the nth digit of the fibonacci sequence
        // it will return 1 for anything < 0 as well...
        // it's calculated recursively and use big.Int since
        // int64 will quickly overflow
        func Fib(n int) *big.Int {
            if n < 0 {
                return nil
            }

            // base case
            if n < 2 {
                memoize[n] = big.NewInt(1)
            }

            // check if we stored it before
            // if so return with no calculation
            if val, ok := memoize[n]; ok {
                return val
            }

            // initialize map then add previous 2 fib values
            memoize[n] = big.NewInt(0)
            memoize[n].Add(memoize[n], Fib(n-1))
            memoize[n].Add(memoize[n], Fib(n-2))

            // return result
            return memoize[n]
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment