Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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

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

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.