diff --git a/DIRECTORY.md b/DIRECTORY.md index 564a7813807..af4b172d60d 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -255,6 +255,7 @@ * [Tanh](https://github.com/TheAlgorithms/Rust/blob/master/src/math/tanh.rs) * [Trapezoidal Integration](https://github.com/TheAlgorithms/Rust/blob/master/src/math/trapezoidal_integration.rs) * [Trial Division](https://github.com/TheAlgorithms/Rust/blob/master/src/math/trial_division.rs) + * [Triangular Number](https://github.com/TheAlgorithms/Rust/blob/master/src/math/triangular_number.rs) * [Trig Functions](https://github.com/TheAlgorithms/Rust/blob/master/src/math/trig_functions.rs) * [Vector Cross Product](https://github.com/TheAlgorithms/Rust/blob/master/src/math/vector_cross_product.rs) * [Zellers Congruence Algorithm](https://github.com/TheAlgorithms/Rust/blob/master/src/math/zellers_congruence_algorithm.rs) diff --git a/src/math/mod.rs b/src/math/mod.rs index 7407465c3b0..2d5d1f30e50 100644 --- a/src/math/mod.rs +++ b/src/math/mod.rs @@ -78,6 +78,7 @@ mod sylvester_sequence; mod tanh; mod trapezoidal_integration; mod trial_division; +mod triangular_number; mod trig_functions; mod vector_cross_product; mod zellers_congruence_algorithm; @@ -170,6 +171,7 @@ pub use self::sylvester_sequence::sylvester; pub use self::tanh::tanh; pub use self::trapezoidal_integration::trapezoidal_integral; pub use self::trial_division::trial_division; +pub use self::triangular_number::triangular_number; pub use self::trig_functions::cosine; pub use self::trig_functions::cosine_no_radian_arg; pub use self::trig_functions::cotan; diff --git a/src/math/triangular_number.rs b/src/math/triangular_number.rs new file mode 100644 index 00000000000..3a9980f5e99 --- /dev/null +++ b/src/math/triangular_number.rs @@ -0,0 +1,36 @@ +// Triangular Numbers: Function to the Nth Triangular Number +// Wikipedia Reference : https://en.wikipedia.org/wiki/Triangular_number + +// This program provides a function to calculate the nth triangular number defined by T_n = 1 + 2 + +// ... + n = (n^2 + 2)/2 = n(n + 1)/2 = (n + 1) choose 2. + +//returns the nth triangular number +pub fn triangular_number(n: u64) -> u64 { + (n | 1) * ((n + 1) / 2) +} + +#[cfg(test)] +mod tests { + use super::*; + + macro_rules! test_triangular_number { + ($($name:ident: $inputs:expr,)*) => { + $( + #[test] + fn $name() { + let (n, expected) =$inputs; + assert_eq!(triangular_number(n), expected); + } + )* + } + } + + test_triangular_number! { + input_0: (0, 0), + input_1: (1, 1), + input_2: (6, 21), + input_3: (10, 55), + input_4: (21, 231), + input_5: (100, 5050), + } +}