iter-prod
cargo devel CI / cargo CI (push) Has been cancelled Details

This commit is contained in:
Christoph J. Scherr 2024-09-09 14:51:32 +02:00
parent 22505d6d96
commit 3e27923d14
Signed by: cscherrNT
GPG Key ID: 8E2B45BC51A27EA7
4 changed files with 47 additions and 0 deletions

4
Cargo.lock generated
View File

@ -2724,6 +2724,10 @@ version = "1.70.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800"
[[package]]
name = "iter-prod"
version = "0.1.0"
[[package]]
name = "itertools"
version = "0.10.5"

View File

@ -30,9 +30,11 @@ members = [
"members/arithmetics",
"members/egui-demo",
"members/rfd-demo",
"members/iter-prod",
]
default-members = [
".",
"members/iter-prod",
"members/rfd-demo",
"members/egui-demo",
"members/arithmetics",

View File

@ -0,0 +1,6 @@
[package]
name = "iter-prod"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,35 @@
fn main() {
let x = 7;
println!("{}", factorial(x));
}
fn factorial(n: u128) -> u128 {
(1..n + 1).product()
}
// does the same as product from the stdlib
#[allow(dead_code)]
fn myprod<T>(iter: T) -> u128
where
T: Iterator<Item = u128>,
{
#[allow(clippy::unnecessary_fold)] // clippy detects that this is just Iter::product
iter.fold(1, |acc, v| acc * v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn works() {
assert_eq!(factorial(7), 5040);
assert_eq!(factorial(9), 362880);
}
#[test]
fn myprod_same_as_real() {
assert_eq!((1..5).product::<u128>(), myprod(1..5));
assert_eq!((1..30).product::<u128>(), myprod(1..30));
// assert_eq!((1..50).product::<u128>(), myprod(1..50)); // u128 overflows here
}
}