当前位置: 首页> 汽车> 报价 > 汉中市建设工程审批_搭建个人网站的两种方法_厦门seo关键词优化培训_竞价代运营外包公司

汉中市建设工程审批_搭建个人网站的两种方法_厦门seo关键词优化培训_竞价代运营外包公司

时间:2025/9/18 6:04:38来源:https://blog.csdn.net/hzether/article/details/143088117 浏览次数: 0次
汉中市建设工程审批_搭建个人网站的两种方法_厦门seo关键词优化培训_竞价代运营外包公司
package mainimport ("fmt""time""math/big"
)// 使用递归和 big.Int 计算阶乘
func FactorialRecursive(n *big.Int) *big.Int {if n.Cmp(big.NewInt(0)) == 0 {return big.NewInt(1)}return new(big.Int).Mul(n, FactorialRecursive(new(big.Int).Sub(n, big.NewInt(1))))
}// 使用迭代和 big.Int 计算阶乘
func FactorialIterative(n *big.Int) *big.Int {result := big.NewInt(1)for i := big.NewInt(2); i.Cmp(n) <= 0; i.Add(i, big.NewInt(1)) {result.Mul(result, i)}return result
}func main() {n := big.NewInt(2000)// 递归方法start := time.Now()resultRecursive := FactorialRecursive(new(big.Int).Set(n))durationRecursive := time.Since(start)fmt.Printf("递归计算 %s 的阶乘结果长度: %d 位\n", n, len(resultRecursive.String()))fmt.Printf("递归计算执行时间: %v\n", durationRecursive)// 迭代方法startIterative := time.Now()resultIterative := FactorialIterative(new(big.Int).Set(n))durationIterative := time.Since(startIterative)fmt.Printf("迭代计算 %s 的阶乘结果长度: %d 位\n", n, len(resultIterative.String()))fmt.Printf("迭代计算执行时间: %v\n", durationIterative)// 验证两种方法的结果是否相同if resultRecursive.Cmp(resultIterative) == 0 {fmt.Println("两种方法的结果相同")} else {fmt.Println("错误:两种方法的结果不同")}
}

结果

PS E:\studygo> go run .\chengji.go
递归计算 2000 的阶乘结果长度: 5736 位
递归计算执行时间: 1.6225ms
迭代计算 2000 的阶乘结果长度: 5736 位
迭代计算执行时间: 514.6µs
两种方法的结果相同
PS E:\studygo> go run .\chengji.go
递归计算 2000 的阶乘结果长度: 5736 位
递归计算执行时间: 1.5059ms
迭代计算 2000 的阶乘结果长度: 5736 位
迭代计算执行时间: 0s
两种方法的结果相同

关键字:汉中市建设工程审批_搭建个人网站的两种方法_厦门seo关键词优化培训_竞价代运营外包公司

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: