find the nth triangular number in rust

To find the nth triangular number in Rust, we can use the following formula:

main.rs
Tn = n * (n + 1) / 2
21 chars
2 lines

where Tn is the nth triangular number.

We can use this formula in a Rust function as follows:

main.rs
fn nth_triangular_number(n: u32) -> u32 {
    n * (n + 1) / 2
}
64 chars
4 lines

This function takes an unsigned 32-bit integer n as input and returns an unsigned 32-bit integer which is the nth triangular number.

We can test this function using Rust's built-in test framework as follows:

main.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_nth_triangular_number() {
        assert_eq!(nth_triangular_number(1), 1);
        assert_eq!(nth_triangular_number(2), 3);
        assert_eq!(nth_triangular_number(3), 6);
        assert_eq!(nth_triangular_number(4), 10);
        assert_eq!(nth_triangular_number(5), 15);
    }
}
349 chars
14 lines

This test module checks if the nth_triangular_number() function returns the correct values for the input values 1 to 5.

related categories

gistlibby LogSnag