gpt4 book ai didi

go - 如何使用 Math/Big int Golang

转载 作者:IT王子 更新时间:2023-10-29 00:36:11 25 4
gpt4 key购买 nike

我正在尝试创建阶乘程序,但当数字太大时,答案就会出错。这是我的代码。我是 math/big 的新手,无法弄清楚如何将它正确地实现到程序中。任何帮助表示赞赏。谢谢。

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

最佳答案

您可以使用 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

关于go - 如何使用 Math/Big int Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42567954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com