find the factorial of a number in rust

Here's an implementation of the factorial function in Rust:

main.rs
fn factorial(n: u64) -> u64 {
    if n == 0 {
        1
    } else {
        n * factorial(n - 1)
    }
}
106 chars
8 lines

This function takes a u64 integer n and returns an u64 integer result. If n is zero, result is set to 1. Otherwise, result is set to n multiplied by the factorial of n-1.

You can call this function for any positive integer n and get the factorial of that number:

main.rs
fn main() {
    let n = 5;
    let result = factorial(n);
    println!("Factorial of {} is {}", n, result);
}
110 chars
6 lines

This will output:

main.rs
Factorial of 5 is 120
22 chars
2 lines

gistlibby LogSnag