Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Math/Big in Go Lang

I am trying to create a factorial program, but when the numbers get too big the answer becomes wrong. Here is my code. I am new to math/big and cannot figure out how to correctly implement it into the program. Any help is appreciated. Thanks.

package main

import (
"fmt"
"os"
"strconv"
"math/big"
)

func main() {
fmt.Print("What integer would you like to to find a total factorial for?")
var userinput string
var userint int
fmt.Scan(&userinput)
userint, err := strconv.Atoi(userinput)
if err != nil {
    fmt.Println("ERROR: Please input an integer")
    os.Exit(2)
}
var efactorial int = 1
var ofactorial int = 1
var tfactorial int
var counter int

for counter = 2; counter <= userint; counter = counter + 2 {
    efactorial = efactorial * counter
}

for counter = 1; counter <= userint; counter = counter + 2 {
    ofactorial = ofactorial * counter
}
fmt.Println("Even factorial is: ", efactorial)
fmt.Println("Odd factorial is: ", ofactorial)

tfactorial = efactorial + ofactorial
fmt.Println("The Total factorial is: ", tfactorial)
}
like image 541
Brantley Avatar asked Mar 02 '17 23:03

Brantley


People also ask

What is big int Golang?

Golang doesn't check for overflows implicitly and so this may lead to unexpected results when a number larger than 64 bits are stored in a int64. To solve this problem, Go provides the Package “big” which implements arbitrary-precision arithmetic (big numbers).

What is int64 in Golang?

int64 is a version of int that only stores signed numeric values composed of up to 64 bits. So, for example, if you try to store a string value in it, or an integer beyond what can be made using 64 bits, the program would return an error or result in an integer overflow.

How big is a big int Golang?

There is no explicit limit. The limit will be your memory or, theoretically, the max array size (2^31 or 2^63, depending on your platform).


1 Answers

You can use big.Int.MulRange to find the product of a range of integers. This is ideal for computing factorials. Here's a complete example that computes 50!

package main

import (
    "fmt"
    "math/big"
)

func main() {
    var f big.Int
    f.MulRange(1, 50)
    fmt.Println(&f)
}

The output:

30414093201713378043612608166064768844377641568960512000000000000
like image 64
Paul Hankin Avatar answered Sep 30 '22 18:09

Paul Hankin