rust - 如何使用迭代器和范围创建阶乘的非递归计算?

标签 rust iterator non-recursive

我遇到了一个不断困扰我的 RuSTLings 练习:

pub fn factorial(num: u64) -> u64 {
    // Complete this function to return factorial of num
    // Do not use:
    // - return
    // For extra fun don't use:
    // - imperative style loops (for, while)
    // - additional variables
    // For the most fun don't use:
    // - recursion
    // Execute `rustlings hint iterators4` for hints.
}

解决方案的提示告诉我...

In an imperative language you might write a for loop to iterate through multiply the values into a mutable variable. Or you might write code more functionally with recursion and a match clause. But you can also use ranges and iterators to solve this in rust.



我试过这种方法,但我错过了一些东西:
if num > 1 {
    (2..=num).map(|n| n * ( n - 1 ) ??? ).???
} else {
    1
}

我必须使用类似 .take_while 的东西吗?而不是 if ?

最佳答案

阶乘定义为从起始数到 1 的所有数的乘积。我们使用该定义和 Iterator::product :

fn factorial(num: u64) -> u64 {
    (1..=num).product()
}

如果你看 the implementationProduct对于整数,您会看到它使用 Iterator::fold 引擎盖下:

impl Product for $a {
    fn product<I: Iterator<Item=Self>>(iter: I) -> Self {
        iter.fold($one, Mul::mul)
    }
}


你可以自己硬编码:
fn factorial(num: u64) -> u64 {
    (1..=num).fold(1, |acc, v| acc * v)
}

也可以看看:
  • How to sum the values in an array, slice, or Vec in Rust?
  • How do I sum a vector using fold?
  • 关于rust - 如何使用迭代器和范围创建阶乘的非递归计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60835646/

    相关文章:

    recursion - 以非递归方式检索二叉树节点的深度

    java - 如何以非递归方式重写 Ackermann 函数?

    python - 非递归 os.walk()

    rust - 为什么这个简单的闭包会失败,而其他两个函数会成功?

    c++ - 使用迭代器遍历 vector 并修改内容

    rust - 无法导入 libc::funcs

    java - 修改迭代内的列表

    python - 如何在 Python 中并行化生成器/迭代器的管道?

    rust - 如何使用Serde在结构中反序列化json格式的结构数组?

    rust - Return Self 避免搬出借用的内容