Skip to content

Commit

Permalink
Add a method that solves the problem: using recursion combined with `…
Browse files Browse the repository at this point in the history
…match` to implement factorial.
  • Loading branch information
1vk3y committed Oct 19, 2024
1 parent 1444cb9 commit 6ae3a05
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion solutions/18_iterators/iterators4.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// 3 possible solutions are presented.
// 4 possible solutions are presented.

// With `for` loop and a mutable variable.
fn factorial_for(num: u64) -> u64 {
Expand Down Expand Up @@ -35,6 +35,14 @@ fn factorial_product(num: u64) -> u64 {
(2..=num).product()
}

// Using recursion in conjunction with the `match` to implement factorial
fn factorial_recursion(num: u64) -> u64 {
match num {
0..=1 => 1,
_ => num * factorial(num - 1),
}
}

fn main() {
// You can optionally experiment here.
}
Expand All @@ -48,25 +56,29 @@ mod tests {
assert_eq!(factorial_for(0), 1);
assert_eq!(factorial_fold(0), 1);
assert_eq!(factorial_product(0), 1);
assert_eq!(factorial_recursion(0), 1);
}

#[test]
fn factorial_of_1() {
assert_eq!(factorial_for(1), 1);
assert_eq!(factorial_fold(1), 1);
assert_eq!(factorial_product(1), 1);
assert_eq!(factorial_recursion(1), 1);
}
#[test]
fn factorial_of_2() {
assert_eq!(factorial_for(2), 2);
assert_eq!(factorial_fold(2), 2);
assert_eq!(factorial_product(2), 2);
assert_eq!(factorial_recursion(2), 2);
}

#[test]
fn factorial_of_4() {
assert_eq!(factorial_for(4), 24);
assert_eq!(factorial_fold(4), 24);
assert_eq!(factorial_product(4), 24);
assert_eq!(factorial_recursion(4), 24);
}
}

0 comments on commit 6ae3a05

Please sign in to comment.