gpt4 book ai didi

go - 如何在 Go 中获得 5000 的阶乘

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

我想在 Go 中计算 5000 的阶乘,但结果为 0,因为结果大于 uint64。但是,我能够在 Node.js 中使用

const BigNumber = require('big-number').

Go 中是否有等效项?

我所做的是:

func RecursiveFactorial(number int) big.Int {
if number >= 1 {
return big.Int{(number) * RecursiveFactorial(number-1)
} else {
return 1
}
}

最佳答案

在 Go 中,使用 math/big 包。

例如,

// OEIS: A000142: Factorial numbers: n! = 1*2*3*4*...*n.
// https://oeis.org/A000045

package main

import (
"fmt"
"math/big"
)

func factorial(x *big.Int) *big.Int {
n := big.NewInt(1)
if x.Cmp(big.NewInt(0)) == 0 {
return n
}
return n.Mul(x, factorial(n.Sub(x, n)))
}

func main() {
fmt.Println(factorial(big.NewInt(5000)))
}

Playground :https://play.golang.org/p/53TmmygltkR

关于go - 如何在 Go 中获得 5000 的阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54951107/

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