find the nth heptagonal number in rust

To find the nth heptagonal number, we can use the formula:

main.rs
H(n) = n(5n-3)/2
17 chars
2 lines

where n is the index of the heptagonal number.

We can implement this formula in rust as follows:

main.rs
fn heptagonal_number(n: u64) -> u64 {
    n * (5 * n - 3) / 2
}
64 chars
4 lines

The heptagonal_number function takes an unsigned 64-bit integer n as input and returns the corresponding heptagonal number as an unsigned 64-bit integer. Note that we use u64 instead of i64 as heptagonal numbers are always positive.

We can then call this function to find the nth heptagonal number as shown below:

main.rs
fn main() {
    let n = 5;
    let h_n = heptagonal_number(n);
    println!("The {}th heptagonal number is: {}", n, h_n);
}
124 chars
6 lines

This will output:

main.rs
The 5th heptagonal number is: 95
33 chars
2 lines

gistlibby LogSnag