How to use Math/Big in Go Lang

时间:2017-03-02 23:30:05

标签: go factorial bigint

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

2 个答案:

答案 0 :(得分:8)

您可以使用big.Int.MulRange查找一系列整数的乘积。这是计算阶乘的理想选择。这是complete example that computes 50!

package main

import (
    "fmt"
    "math/big"
)

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

输出:

30414093201713378043612608166064768844377641568960512000000000000

答案 1 :(得分:1)

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))
}
相关问题