find the nth lucas number in rust

Lucas numbers are a sequence of numbers similar to the Fibonacci sequence. The sequence starts with 2 and 1 and then each number is the sum of its two preceding numbers. In Rust, you can write a recursive function to find the nth Lucas number using the formula:

L_n = L_{n-1} + L_{n-2}

where L_0 = 2 and L_1 = 1.

Here's an implementation of the recursive function:

main.rs
fn lucas(n: u32) -> u32 {
    match n {
        0 => 2,
        1 => 1,
        _ => lucas(n-1) + lucas(n-2),
    }
}
118 chars
8 lines

This function takes an argument n which is the number of the Lucas number to find. It returns the nth Lucas number.

To use this function, you can simply call it with the desired value of n:

main.rs
fn main() {
    let n = 10;
    let lucas_n = lucas(n);
    println!("The {}th Lucas number is: {}", n, lucas_n);
}
116 chars
6 lines

This will output:

main.rs
The 10th Lucas number is: 123
30 chars
2 lines

gistlibby LogSnag