1- // 3 possible solutions are presented.
1+ // 4 possible solutions are presented.
22
33// With `for` loop and a mutable variable.
44fn factorial_for ( num : u64 ) -> u64 {
@@ -35,6 +35,14 @@ fn factorial_product(num: u64) -> u64 {
3535 ( 2 ..=num) . product ( )
3636}
3737
38+ // Using recursion in conjunction with the `match` to implement factorial
39+ fn factorial_recursion ( num : u64 ) -> u64 {
40+ match num {
41+ 0 ..=1 => 1 ,
42+ _ => num * factorial ( num - 1 ) ,
43+ }
44+ }
45+
3846fn main ( ) {
3947 // You can optionally experiment here.
4048}
@@ -48,25 +56,29 @@ mod tests {
4856 assert_eq ! ( factorial_for( 0 ) , 1 ) ;
4957 assert_eq ! ( factorial_fold( 0 ) , 1 ) ;
5058 assert_eq ! ( factorial_product( 0 ) , 1 ) ;
59+ assert_eq ! ( factorial_recursion( 0 ) , 1 ) ;
5160 }
5261
5362 #[ test]
5463 fn factorial_of_1 ( ) {
5564 assert_eq ! ( factorial_for( 1 ) , 1 ) ;
5665 assert_eq ! ( factorial_fold( 1 ) , 1 ) ;
5766 assert_eq ! ( factorial_product( 1 ) , 1 ) ;
67+ assert_eq ! ( factorial_recursion( 1 ) , 1 ) ;
5868 }
5969 #[ test]
6070 fn factorial_of_2 ( ) {
6171 assert_eq ! ( factorial_for( 2 ) , 2 ) ;
6272 assert_eq ! ( factorial_fold( 2 ) , 2 ) ;
6373 assert_eq ! ( factorial_product( 2 ) , 2 ) ;
74+ assert_eq ! ( factorial_recursion( 2 ) , 2 ) ;
6475 }
6576
6677 #[ test]
6778 fn factorial_of_4 ( ) {
6879 assert_eq ! ( factorial_for( 4 ) , 24 ) ;
6980 assert_eq ! ( factorial_fold( 4 ) , 24 ) ;
7081 assert_eq ! ( factorial_product( 4 ) , 24 ) ;
82+ assert_eq ! ( factorial_recursion( 4 ) , 24 ) ;
7183 }
7284}
0 commit comments