find the nth octagonal number in rust

To find the nth octagonal number, we need to use the formula n(3n-2), where n is the nth term in the sequence. We can easily create a function in Rust to calculate the nth octagonal number using this formula.

main.rs
fn nth_octagonal_number(n: u32) -> u32 {
    n * (3 * n - 2)
}
63 chars
4 lines

This function takes an integer n as input and returns the corresponding nth octagonal number as an integer.

Here's an example usage of the function:

main.rs
fn main() {
    let n = 5;
    let octagonal_number = nth_octagonal_number(n);
    println!("The {}th octagonal number is {}", n, octagonal_number);
}
151 chars
6 lines

Output:

main.rs
The 5th octagonal number is 141
32 chars
2 lines

gistlibby LogSnag