find the nth pentagonal number in rust

To find the nth pentagonal number we can use the formula: Pn = n(3n-1)/2

We can define a function to implement this formula as follows:

main.rs
fn pentagonal(n: u32) -> u32 {
    n * (3 * n - 1) / 2
}
57 chars
4 lines

This function takes an argument n of type u32 and returns the nth pentagonal number as output.

We can test our function by calling it with different values of n as follows:

main.rs
fn main() {
    // Find the 5th pentagonal number
    let n = 5;
    let p = pentagonal(n);
    println!("The {}th pentagonal number is {}", n, p);
    
    // Find the 10th pentagonal number
    let n = 10;
    let p = pentagonal(n);
    println!("The {}th pentagonal number is {}", n, p);
}
293 chars
12 lines

This will output:

main.rs
The 5th pentagonal number is 35
The 10th pentagonal number is 145
66 chars
3 lines

Note that since we are using integer arithmetic, our function will return the pentagonal number as an integer. If we need to find pentagonal numbers with higher values of n we should use a larger integer type like u64.

gistlibby LogSnag