Sure, here is a Rust function to find the factorial of a given number using recursion:
Rust
fn factorial(n: i32) -> i32 {
// Base case.
if n == 0 {
return 1;
}
// Recursive case.
return n * factorial(n - 1);
}
fn main() {
// Get the number from the user.
let mut number = String::new();
io::stdin().read_line(&mut number).unwrap();
// Convert the number to an integer.
let number: i32 = number.trim().parse().unwrap();
// Find the factorial of the number.
let factorial = factorial(number);
// Print the factorial.
println!("The factorial of {} is: {}", number, factorial);
}
This function first defines a base case. The base case is when the number is 0. In this case, the function returns 1. Otherwise, the function defines a recursive case. The recursive case is when the number is greater than 0. In this case, the function multiplies the number by the factorial of the number minus 1. Finally, the function returns the factorial.
To run this program, you can save it as a .rs file and then compile and run it using the following commands:
Code snippet
rustc factorial.rs
./factorial
This will prompt you to enter a number. Enter a number and press Enter. The program will then print the factorial of the number.
For example, if you enter the number 5, the program will print the following output:
Code snippet
The factorial of 5 is: 120
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust function to find the factorial of a given number using recursion:
Rust
This function first defines a base case. The base case is when the number is 0. In this case, the function returns 1. Otherwise, the function defines a recursive case. The recursive case is when the number is greater than 0. In this case, the function multiplies the number by the factorial of the number minus 1. Finally, the function returns the factorial.
To run this program, you can save it as a
.rsfile and then compile and run it using the following commands:Code snippet
This will prompt you to enter a number. Enter a number and press Enter. The program will then print the factorial of the number.
For example, if you enter the number 5, the program will print the following output:
Code snippet