go中阶乘实现时递归及迭代方式的比较

package main

import (
    "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
两种方法的结果相同

上一篇:【2024年最新】AI教程-AI大模型知识,零基础入门到精通
下一篇:kuberctl工具汇总