# Problem with factorial recursion

I'm new to Rust programming, i ran into the problem with pass by reference using recursion method for factorial program,
factorial using for loop works fine but recursion is not,
following example shows the function has same signature but works differently, can anyone explain where did i made wrong declaration or the entire program needs changes..
using for loop: //it works

``````fn main() {
let mut num:u32 = 5;
let res=modify(&mut num);
println!("Function return value:{:?},\nmain function val:{:?}",res, num);
}

fn modify(num:&mut u32)->u32{

let mut fact:u32 =1;
for i in 1..*num+1{
fact *= i;
}
*num =fact;
*num
}
``````

Result:
Function return value:120,
main function val:120

using recursion://not working as expected..

``````fn main() {
let mut num:u32 = 5;
let res=modify(&mut num);
println!("Function return value:{:?},\nmain function val:{:?}",res, num);
}

fn modify(num:&mut u32)->u32{

if *num == 1{
*num
}else{
*num * modify(&mut (*num -1))
}
}
``````

Result:
Function return value:120,
main function val:5

The version with a loop contains the line

``````*num = fact;
``````

while the recursive version never modifies the value behind the reference `num`.

Note that the usage of mutable references for this function seems highly unnecessary in practice, you should probably just write a function `fn factorial(num: u32) -> u32 { … }` passing the numbers by-value.

loop

``````fn main() {
let num: u32 = 5;
let res = factorial(num);
println!(
"Function return value: {:?},\n\
main function val: {:?}",
res, num
);
}

fn factorial(num: u32) -> u32 {
let mut fact: u32 = 1;
for i in 1..=num {
fact *= i;
}
fact
}
``````

recursion

``````fn main() {
let num: u32 = 5;
let res = factorial(num);
println!(
"Function return value: {:?},\n\
main function val: {:?}",
res, num
);
}

fn factorial(num: u32) -> u32 {
if num == 0 {
1
} else {
num * factorial(num - 1)
}
}
``````
2 Likes

Thank you for the explanation , i think i went overboard for a simple problem it seems, and i might have to learn the necessity of usage of mutable references when necessary.. Edit:
a small change needed in your code sir, if num == 0 to if num == 1

Actually, that one was intentional. For the mathematical factorial operation, `0! = 1`, and then `1! = 1·(0!) = 1·1 = 1`. The check `num == 0` makes the function behave properly on input zero.

Edit: Actually, should’ve returned `1` instead of `num` though I fixed the code above now:

``````    if num == 0 {
-       num
+       1
} else {
num * factorial(num - 1)
}
``````

(Note to self: Next time double-check the output of the program before sharing it.)

Understood sir, This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.