Brantley
Brantley

Reputation: 69

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)
}

Upvotes: 7

Views: 4950

Answers (2)

Paul Hankin
Paul Hankin

Reputation: 58271

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

Upvotes: 11

Benjamin Kadish
Benjamin Kadish

Reputation: 1500

you want ofactorial and tfactorial to be of type big.Int

ofactorial := big.NewInt(1)
tfactorial := big.NewInt(0)

Then you will want to use the methods from the big package for multiplying Ints found here

your for loop will look something like

for counter = 2; counter <= userint; counter = counter + 2 {
    efactorial.Mul(efactorial * big.NewInt(counter))
}

Upvotes: 1

Related Questions