repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/collatz_sequence.rs
src/math/collatz_sequence.rs
// collatz conjecture : https://en.wikipedia.org/wiki/Collatz_conjecture pub fn sequence(mut n: usize) -> Option<Vec<usize>> { if n == 0 { return None; } let mut list: Vec<usize> = vec![]; while n != 1 { list.push(n); if n.is_multiple_of(2) { n /= 2; } else { n = 3 * n + 1; } } list.push(n); Some(list) } #[cfg(test)] mod tests { use super::sequence; #[test] fn validity_check() { assert_eq!(sequence(10).unwrap(), [10, 5, 16, 8, 4, 2, 1]); assert_eq!( sequence(15).unwrap(), [15, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1] ); assert_eq!(sequence(0).unwrap_or_else(|| vec![0]), [0]); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/infix_to_postfix.rs
src/math/infix_to_postfix.rs
#[derive(Debug, Clone, PartialEq, Eq)] pub enum InfixToPostfixError { UnknownCharacter(char), UnmatchedParent, } /// Function to convert [infix expression](https://en.wikipedia.org/wiki/Infix_notation) to [postfix expression](https://en.wikipedia.org/wiki/Reverse_Polish_notation) pub fn infix_to_postfix(infix: &str) -> Result<String, InfixToPostfixError> { let mut postfix = String::new(); let mut stack: Vec<char> = Vec::new(); // Define the precedence of operators let precedence = |op: char| -> u8 { match op { '+' | '-' => 1, '*' | '/' => 2, '^' => 3, _ => 0, } }; for token in infix.chars() { match token { c if c.is_alphanumeric() => { postfix.push(c); } '(' => { stack.push('('); } ')' => { while let Some(top) = stack.pop() { if top == '(' { break; } postfix.push(top); } } '+' | '-' | '*' | '/' | '^' => { while let Some(top) = stack.last() { if *top == '(' || precedence(*top) < precedence(token) { break; } postfix.push(stack.pop().unwrap()); } stack.push(token); } other => return Err(InfixToPostfixError::UnknownCharacter(other)), } } while let Some(top) = stack.pop() { if top == '(' { return Err(InfixToPostfixError::UnmatchedParent); } postfix.push(top); } Ok(postfix) } #[cfg(test)] mod tests { use super::*; macro_rules! test_infix_to_postfix { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let (infix, expected) = $inputs; assert_eq!(infix_to_postfix(infix), expected) } )* } } test_infix_to_postfix! { single_symbol: ("x", Ok(String::from("x"))), simple_sum: ("x+y", Ok(String::from("xy+"))), multiply_sum_left: ("x*(y+z)", Ok(String::from("xyz+*"))), multiply_sum_right: ("(x+y)*z", Ok(String::from("xy+z*"))), multiply_two_sums: ("(a+b)*(c+d)", Ok(String::from("ab+cd+*"))), product_and_power: ("a*b^c", Ok(String::from("abc^*"))), power_and_product: ("a^b*c", Ok(String::from("ab^c*"))), product_of_powers: ("(a*b)^c", Ok(String::from("ab*c^"))), product_in_exponent: ("a^(b*c)", Ok(String::from("abc*^"))), regular_0: ("a-b+c-d*e", Ok(String::from("ab-c+de*-"))), regular_1: ("a*(b+c)+d/(e+f)", Ok(String::from("abc+*def+/+"))), regular_2: ("(a-b+c)*(d+e*f)", Ok(String::from("ab-c+def*+*"))), unknown_character: ("(a-b)*#", Err(InfixToPostfixError::UnknownCharacter('#'))), unmatched_paren: ("((a-b)", Err(InfixToPostfixError::UnmatchedParent)), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/sum_of_digits.rs
src/math/sum_of_digits.rs
/// Iteratively sums the digits of a signed integer /// /// ## Arguments /// /// * `num` - The number to sum the digits of /// /// ## Examples /// /// ``` /// use the_algorithms_rust::math::sum_digits_iterative; /// /// assert_eq!(10, sum_digits_iterative(1234)); /// assert_eq!(12, sum_digits_iterative(-246)); /// ``` pub fn sum_digits_iterative(num: i32) -> u32 { // convert to unsigned integer let mut num = num.unsigned_abs(); // initialize sum let mut result: u32 = 0; // iterate through digits while num > 0 { // extract next digit and add to sum result += num % 10; num /= 10; // chop off last digit } result } /// Recursively sums the digits of a signed integer /// /// ## Arguments /// /// * `num` - The number to sum the digits of /// /// ## Examples /// /// ``` /// use the_algorithms_rust::math::sum_digits_recursive; /// /// assert_eq!(10, sum_digits_recursive(1234)); /// assert_eq!(12, sum_digits_recursive(-246)); /// ``` pub fn sum_digits_recursive(num: i32) -> u32 { // convert to unsigned integer let num = num.unsigned_abs(); // base case if num < 10 { return num; } // recursive case: add last digit to sum of remaining digits num % 10 + sum_digits_recursive((num / 10) as i32) } #[cfg(test)] mod tests { mod iterative { // import relevant sum_digits function use super::super::sum_digits_iterative as sum_digits; #[test] fn zero() { assert_eq!(0, sum_digits(0)); } #[test] fn positive_number() { assert_eq!(1, sum_digits(1)); assert_eq!(10, sum_digits(1234)); assert_eq!(14, sum_digits(42161)); assert_eq!(6, sum_digits(500010)); } #[test] fn negative_number() { assert_eq!(1, sum_digits(-1)); assert_eq!(12, sum_digits(-246)); assert_eq!(2, sum_digits(-11)); assert_eq!(14, sum_digits(-42161)); assert_eq!(6, sum_digits(-500010)); } #[test] fn trailing_zeros() { assert_eq!(1, sum_digits(1000000000)); assert_eq!(3, sum_digits(300)); } } mod recursive { // import relevant sum_digits function use super::super::sum_digits_recursive as sum_digits; #[test] fn zero() { assert_eq!(0, sum_digits(0)); } #[test] fn positive_number() { assert_eq!(1, sum_digits(1)); assert_eq!(10, sum_digits(1234)); assert_eq!(14, sum_digits(42161)); assert_eq!(6, sum_digits(500010)); } #[test] fn negative_number() { assert_eq!(1, sum_digits(-1)); assert_eq!(12, sum_digits(-246)); assert_eq!(2, sum_digits(-11)); assert_eq!(14, sum_digits(-42161)); assert_eq!(6, sum_digits(-500010)); } #[test] fn trailing_zeros() { assert_eq!(1, sum_digits(1000000000)); assert_eq!(3, sum_digits(300)); } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/newton_raphson.rs
src/math/newton_raphson.rs
pub fn find_root(f: fn(f64) -> f64, fd: fn(f64) -> f64, guess: f64, iterations: i32) -> f64 { let mut result = guess; for _ in 0..iterations { result = iteration(f, fd, result); } result } pub fn iteration(f: fn(f64) -> f64, fd: fn(f64) -> f64, guess: f64) -> f64 { guess - f(guess) / fd(guess) } #[cfg(test)] mod tests { use super::*; fn math_fn(x: f64) -> f64 { x.cos() - (x * x * x) } fn math_fnd(x: f64) -> f64 { -x.sin() - 3.0 * (x * x) } #[test] fn basic() { assert_eq!(find_root(math_fn, math_fnd, 0.5, 6), 0.8654740331016144); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/pascal_triangle.rs
src/math/pascal_triangle.rs
/// ## Pascal's triangle problem /// /// pascal_triangle(num_rows) returns the first num_rows of Pascal's triangle.\ /// About Pascal's triangle: <https://en.wikipedia.org/wiki/Pascal%27s_triangle> /// /// # Arguments: /// * `num_rows`: number of rows of triangle /// /// # Complexity /// - time complexity: O(n^2), /// - space complexity: O(n^2), pub fn pascal_triangle(num_rows: i32) -> Vec<Vec<i32>> { let mut ans: Vec<Vec<i32>> = vec![]; for i in 1..=num_rows { let mut vec: Vec<i32> = vec![1]; let mut res: i32 = 1; for k in 1..i { res *= i - k; res /= k; vec.push(res); } ans.push(vec); } ans } #[cfg(test)] mod tests { use super::pascal_triangle; #[test] fn test() { assert_eq!(pascal_triangle(3), vec![vec![1], vec![1, 1], vec![1, 2, 1]]); assert_eq!( pascal_triangle(4), vec![vec![1], vec![1, 1], vec![1, 2, 1], vec![1, 3, 3, 1]] ); assert_eq!( pascal_triangle(5), vec![ vec![1], vec![1, 1], vec![1, 2, 1], vec![1, 3, 3, 1], vec![1, 4, 6, 4, 1] ] ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/sum_of_geometric_progression.rs
src/math/sum_of_geometric_progression.rs
// Author : cyrixninja // Find the Sum of Geometric Progression // Wikipedia: https://en.wikipedia.org/wiki/Geometric_progression pub fn sum_of_geometric_progression(first_term: f64, common_ratio: f64, num_of_terms: i32) -> f64 { if common_ratio == 1.0 { // Formula for sum if the common ratio is 1 return (num_of_terms as f64) * first_term; } // Formula for finding the sum of n terms of a Geometric Progression (first_term / (1.0 - common_ratio)) * (1.0 - common_ratio.powi(num_of_terms)) } #[cfg(test)] mod tests { use super::*; macro_rules! test_sum_of_geometric_progression { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let (first_term, common_ratio, num_of_terms, expected) = $inputs; assert_eq!(sum_of_geometric_progression(first_term, common_ratio, num_of_terms), expected); } )* } } test_sum_of_geometric_progression! { regular_input_0: (1.0, 2.0, 10, 1023.0), regular_input_1: (1.0, 10.0, 5, 11111.0), regular_input_2: (9.0, 2.5, 5, 579.9375), common_ratio_one: (10.0, 1.0, 3, 30.0), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/armstrong_number.rs
src/math/armstrong_number.rs
pub fn is_armstrong_number(number: u32) -> bool { let mut digits: Vec<u32> = Vec::new(); let mut num: u32 = number; loop { digits.push(num % 10); num /= 10; if num == 0 { break; } } let sum_nth_power_of_digits: u32 = digits .iter() .map(|digit| digit.pow(digits.len() as u32)) .sum(); sum_nth_power_of_digits == number } #[cfg(test)] mod tests { use super::*; #[test] fn one_digit_armstrong_number() { assert!(is_armstrong_number(1)) } #[test] fn two_digit_numbers_are_not_armstrong_numbers() { assert!(!is_armstrong_number(15)) } #[test] fn three_digit_armstrong_number() { assert!(is_armstrong_number(153)) } #[test] fn three_digit_non_armstrong_number() { assert!(!is_armstrong_number(105)) } #[test] fn big_armstrong_number() { assert!(is_armstrong_number(912985153)) } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/linear_sieve.rs
src/math/linear_sieve.rs
/* Linear Sieve algorithm: Time complexity is indeed O(n) with O(n) memory, but the sieve generally runs slower than a well implemented sieve of Eratosthenes. Some use cases are: - factorizing any number k in the sieve in O(log(k)) - calculating arbitrary multiplicative functions on sieve numbers without increasing the time complexity - As a by product, all prime numbers less than `max_number` are stored in `primes` vector. */ pub struct LinearSieve { max_number: usize, pub primes: Vec<usize>, pub minimum_prime_factor: Vec<usize>, } impl LinearSieve { pub const fn new() -> Self { LinearSieve { max_number: 0, primes: vec![], minimum_prime_factor: vec![], } } pub fn prepare(&mut self, max_number: usize) -> Result<(), &'static str> { if max_number <= 1 { return Err("Sieve size should be more than 1"); } if self.max_number > 0 { return Err("Sieve already initialized"); } self.max_number = max_number; self.minimum_prime_factor.resize(max_number + 1, 0); for i in 2..=max_number { if self.minimum_prime_factor[i] == 0 { self.minimum_prime_factor[i] = i; self.primes.push(i); /* if needed, a multiplicative function can be calculated for this prime number here: function[i] = base_case(i); */ } for p in self.primes.iter() { let mlt = (*p) * i; if *p > i || mlt > max_number { break; } self.minimum_prime_factor[mlt] = *p; /* multiplicative function for mlt can be calculated here: if i % p: function[mlt] = add_to_prime_exponent(function[i], i, p); else: function[mlt] = function[i] * function[p] */ } } Ok(()) } pub fn factorize(&self, mut number: usize) -> Result<Vec<usize>, &'static str> { if number > self.max_number { return Err("Number is too big, its minimum_prime_factor was not calculated"); } if number == 0 { return Err("Number is zero"); } let mut result: Vec<usize> = Vec::new(); while number > 1 { result.push(self.minimum_prime_factor[number]); number /= self.minimum_prime_factor[number]; } Ok(result) } } impl Default for LinearSieve { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use super::LinearSieve; #[test] fn small_primes_list() { let mut ls = LinearSieve::new(); ls.prepare(25).unwrap(); assert_eq!(ls.primes, vec![2, 3, 5, 7, 11, 13, 17, 19, 23]); } #[test] fn divisible_by_mpf() { let mut ls = LinearSieve::new(); ls.prepare(1000).unwrap(); for i in 2..=1000 { let div = i / ls.minimum_prime_factor[i]; assert_eq!(i % ls.minimum_prime_factor[i], 0); if div == 1 { // Number must be prime assert!(ls.primes.binary_search(&i).is_ok()); } } } #[test] fn check_factorization() { let mut ls = LinearSieve::new(); ls.prepare(1000).unwrap(); for i in 1..=1000 { let factorization = ls.factorize(i).unwrap(); let mut product = 1usize; for (idx, p) in factorization.iter().enumerate() { assert!(ls.primes.binary_search(p).is_ok()); product *= *p; if idx > 0 { assert!(*p >= factorization[idx - 1]); } } assert_eq!(product, i); } } #[test] fn check_number_of_primes() { let mut ls = LinearSieve::new(); ls.prepare(100_000).unwrap(); assert_eq!(ls.primes.len(), 9592); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/fast_power.rs
src/math/fast_power.rs
/// fast_power returns the result of base^power mod modulus pub fn fast_power(mut base: usize, mut power: usize, modulus: usize) -> usize { assert!(base >= 1); let mut res = 1; while power > 0 { if power & 1 == 1 { res = (res * base) % modulus; } base = (base * base) % modulus; power >>= 1; } res } #[cfg(test)] mod tests { use super::*; #[test] fn test() { const MOD: usize = 1000000007; assert_eq!(fast_power(2, 1, MOD), 2); assert_eq!(fast_power(2, 2, MOD), 4); assert_eq!(fast_power(2, 4, MOD), 16); assert_eq!(fast_power(3, 4, MOD), 81); assert_eq!(fast_power(2, 100, MOD), 976371285); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/amicable_numbers.rs
src/math/amicable_numbers.rs
// Operations based around amicable numbers // Suports u32 but should be interchangable with other types // Wikipedia reference: https://en.wikipedia.org/wiki/Amicable_numbers // Returns vec of amicable pairs below N // N must be positive pub fn amicable_pairs_under_n(n: u32) -> Option<Vec<(u32, u32)>> { let mut factor_sums = vec![0; n as usize]; // Make a list of the sum of the factors of each number below N for i in 1..n { for j in (i * 2..n).step_by(i as usize) { factor_sums[j as usize] += i; } } // Default value of (0, 0) if no pairs are found let mut out = vec![(0, 0)]; // Check if numbers are amicable then append for (i, x) in factor_sums.iter().enumerate() { if (*x < n) && (factor_sums[*x as usize] == i as u32) && (*x > i as u32) { out.push((i as u32, *x)); } } // Check if anything was added to the vec, if so remove the (0, 0) and return if out.len() == 1 { None } else { out.remove(0); Some(out) } } #[cfg(test)] mod tests { use super::*; #[test] pub fn test_amicable_numbers_below_n() { // First 10 amicable numbers, sorted (low, high) let expected_result = vec![ (220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368), (10744, 10856), (12285, 14595), (17296, 18416), (63020, 76084), (66928, 66992), ]; // Generate pairs under 100,000 let mut result = amicable_pairs_under_n(100_000).unwrap(); // There should be 13 pairs under 100,000 assert_eq!(result.len(), 13); // Check the first 10 against known values result = result[..10].to_vec(); assert_eq!(result, expected_result); // N that does not have any amicable pairs below it, the result should be None assert_eq!(amicable_pairs_under_n(100), None); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/huber_loss.rs
src/math/huber_loss.rs
//! # Huber Loss Function //! //! The `huber_loss` function calculates the Huber loss, which is a robust loss function used in machine learning, particularly in regression problems. //! //! Huber loss combines the benefits of mean squared error (MSE) and mean absolute error (MAE). It behaves like MSE when the difference between actual and predicted values is small (less than a specified `delta`), and like MAE when the difference is large. //! //! ## Formula //! //! For a pair of actual and predicted values, represented as vectors `actual` and `predicted`, and a specified `delta` value, the Huber loss is calculated as: //! //! - If the absolute difference between `actual[i]` and `predicted[i]` is less than or equal to `delta`, the loss is `0.5 * (actual[i] - predicted[i])^2`. //! - If the absolute difference is greater than `delta`, the loss is `delta * |actual[i] - predicted[i]| - 0.5 * delta`. //! //! The total loss is the sum of individual losses over all elements. //! //! ## Huber Loss Function Implementation //! //! This implementation takes two references to vectors of f64 values, `actual` and `predicted`, and a `delta` value. It returns the Huber loss between them, providing a robust measure of dissimilarity between actual and predicted values. //! pub fn huber_loss(actual: &[f64], predicted: &[f64], delta: f64) -> f64 { let mut loss: Vec<f64> = Vec::new(); for (a, p) in actual.iter().zip(predicted.iter()) { if (a - p).abs() <= delta { loss.push(0.5 * (a - p).powf(2.)); } else { loss.push(delta * (a - p).abs() - (0.5 * delta)); } } loss.iter().sum() } #[cfg(test)] mod tests { use super::*; #[test] fn test_huber_loss() { let test_vector_actual = vec![1.0, 2.0, 3.0, 4.0, 5.0]; let test_vector = vec![5.0, 7.0, 9.0, 11.0, 13.0]; assert_eq!(huber_loss(&test_vector_actual, &test_vector, 1.0), 27.5); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/leaky_relu.rs
src/math/leaky_relu.rs
//! # Leaky ReLU Function //! //! The `leaky_relu` function computes the Leaky Rectified Linear Unit (ReLU) values of a given vector //! of f64 numbers with a specified alpha parameter. //! //! The Leaky ReLU activation function is commonly used in neural networks to introduce a small negative //! slope (controlled by the alpha parameter) for the negative input values, preventing neurons from dying //! during training. //! //! ## Formula //! //! For a given input vector `x` and an alpha parameter `alpha`, the Leaky ReLU function computes the output //! `y` as follows: //! //! `y_i = { x_i if x_i >= 0, alpha * x_i if x_i < 0 }` //! //! ## Leaky ReLU Function Implementation //! //! This implementation takes a reference to a vector of f64 values and an alpha parameter, and returns a new //! vector with the Leaky ReLU transformation applied to each element. The input vector is not altered. //! pub fn leaky_relu(vector: &Vec<f64>, alpha: f64) -> Vec<f64> { let mut _vector = vector.to_owned(); for value in &mut _vector { if value < &mut 0. { *value *= alpha; } } _vector } #[cfg(test)] mod tests { use super::*; #[test] fn test_leaky_relu() { let test_vector = vec![-10., 2., -3., 4., -5., 10., 0.05]; let alpha = 0.01; assert_eq!( leaky_relu(&test_vector, alpha), vec![-0.1, 2.0, -0.03, 4.0, -0.05, 10.0, 0.05] ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/abs.rs
src/math/abs.rs
/// This function returns the absolute value of a number.\ /// The absolute value of a number is the non-negative value of the number, regardless of its sign.\ /// /// Wikipedia: <https://en.wikipedia.org/wiki/Absolute_value> pub fn abs<T>(num: T) -> T where T: std::ops::Neg<Output = T> + PartialOrd + Copy + num_traits::Zero, { if num < T::zero() { return -num; } num } #[cfg(test)] mod test { use super::*; #[test] fn test_negative_number_i32() { assert_eq!(69, abs(-69)); } #[test] fn test_negative_number_f64() { assert_eq!(69.69, abs(-69.69)); } #[test] fn zero() { assert_eq!(0.0, abs(0.0)); } #[test] fn positive_number() { assert_eq!(69.69, abs(69.69)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/prime_check.rs
src/math/prime_check.rs
pub fn prime_check(num: usize) -> bool { if (num > 1) & (num < 4) { return true; } else if (num < 2) || (num.is_multiple_of(2)) { return false; } let stop: usize = (num as f64).sqrt() as usize + 1; for i in (3..stop).step_by(2) { if num.is_multiple_of(i) { return false; } } true } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert!(prime_check(3)); assert!(prime_check(7)); assert!(prime_check(11)); assert!(prime_check(2003)); assert!(!prime_check(4)); assert!(!prime_check(6)); assert!(!prime_check(21)); assert!(!prime_check(2004)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/karatsuba_multiplication.rs
src/math/karatsuba_multiplication.rs
/* Finds the product of two numbers using Karatsuba Algorithm */ use std::cmp::max; const TEN: i128 = 10; pub fn multiply(num1: i128, num2: i128) -> i128 { _multiply(num1, num2) } fn _multiply(num1: i128, num2: i128) -> i128 { if num1 < 10 || num2 < 10 { return num1 * num2; } let mut num1_str = num1.to_string(); let mut num2_str = num2.to_string(); let n = max(num1_str.len(), num2_str.len()); num1_str = normalize(num1_str, n); num2_str = normalize(num2_str, n); let a = &num1_str[0..n / 2]; let b = &num1_str[n / 2..]; let c = &num2_str[0..n / 2]; let d = &num2_str[n / 2..]; let ac = _multiply(a.parse().unwrap(), c.parse().unwrap()); let bd = _multiply(b.parse().unwrap(), d.parse().unwrap()); let a_b: i128 = a.parse::<i128>().unwrap() + b.parse::<i128>().unwrap(); let c_d: i128 = c.parse::<i128>().unwrap() + d.parse::<i128>().unwrap(); let ad_bc = _multiply(a_b, c_d) - (ac + bd); let m = n / 2 + n % 2; (TEN.pow(2 * m as u32) * ac) + (TEN.pow(m as u32) * ad_bc) + (bd) } fn normalize(mut a: String, n: usize) -> String { let padding = n.saturating_sub(a.len()); a.insert_str(0, &"0".repeat(padding)); a } #[cfg(test)] mod test { use super::*; #[test] fn test_1() { let n1: i128 = 314159265; let n2: i128 = 314159265; let ans = multiply(n1, n2); assert_eq!(ans, n1 * n2); } #[test] fn test_2() { let n1: i128 = 3141592653589793232; let n2: i128 = 2718281828459045233; let ans = multiply(n1, n2); assert_eq!(ans, n1 * n2); } #[test] fn test_3() { let n1: i128 = 123456789; let n2: i128 = 101112131415; let ans = multiply(n1, n2); assert_eq!(ans, n1 * n2); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/trapezoidal_integration.rs
src/math/trapezoidal_integration.rs
pub fn trapezoidal_integral<F>(a: f64, b: f64, f: F, precision: u32) -> f64 where F: Fn(f64) -> f64, { let delta = (b - a) / precision as f64; (0..precision) .map(|trapezoid| { let left_side = a + (delta * trapezoid as f64); let right_side = left_side + delta; 0.5 * (f(left_side) + f(right_side)) * delta }) .sum() } #[cfg(test)] mod tests { use super::*; macro_rules! test_trapezoidal_integral { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let (a, b, f, prec, expected, eps) = $inputs; let actual = trapezoidal_integral(a, b, f, prec); assert!((actual - expected).abs() < eps); } )* } } test_trapezoidal_integral! { basic_0: (0.0, 1.0, |x: f64| x.powi(2), 1000, 1.0/3.0, 0.0001), basic_0_higher_prec: (0.0, 1.0, |x: f64| x.powi(2), 10000, 1.0/3.0, 0.00001), basic_1: (-1.0, 1.0, |x: f64| x.powi(2), 10000, 2.0/3.0, 0.00001), basic_1_higher_prec: (-1.0, 1.0, |x: f64| x.powi(2), 100000, 2.0/3.0, 0.000001), flipped_limits: (1.0, 0.0, |x: f64| x.powi(2), 10000, -1.0/3.0, 0.00001), empty_range: (0.5, 0.5, |x: f64| x.powi(2), 100, 0.0, 0.0000001), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/modular_exponential.rs
src/math/modular_exponential.rs
/// Calculate the greatest common divisor (GCD) of two numbers and the /// coefficients of Bézout's identity using the Extended Euclidean Algorithm. /// /// # Arguments /// /// * `a` - One of the numbers to find the GCD of /// * `m` - The other number to find the GCD of /// /// # Returns /// /// A tuple (gcd, x1, x2) such that: /// gcd - the greatest common divisor of a and m. /// x1, x2 - the coefficients such that `a * x1 + m * x2` is equivalent to `gcd` modulo `m`. pub fn gcd_extended(a: i64, m: i64) -> (i64, i64, i64) { if a == 0 { (m, 0, 1) } else { let (gcd, x1, x2) = gcd_extended(m % a, a); let x = x2 - (m / a) * x1; (gcd, x, x1) } } /// Find the modular multiplicative inverse of a number modulo `m`. /// /// # Arguments /// /// * `b` - The number to find the modular inverse of /// * `m` - The modulus /// /// # Returns /// /// The modular inverse of `b` modulo `m`. /// /// # Panics /// /// Panics if the inverse does not exist (i.e., `b` and `m` are not coprime). pub fn mod_inverse(b: i64, m: i64) -> i64 { let (gcd, x, _) = gcd_extended(b, m); if gcd == 1 { // Ensure the modular inverse is positive (x % m + m) % m } else { panic!("Inverse does not exist"); } } /// Perform modular exponentiation of a number raised to a power modulo `m`. /// This function handles both positive and negative exponents. /// /// # Arguments /// /// * `base` - The base number to be raised to the `power` /// * `power` - The exponent to raise the `base` to /// * `modulus` - The modulus to perform the operation under /// /// # Returns /// /// The result of `base` raised to `power` modulo `modulus`. pub fn modular_exponential(base: i64, mut power: i64, modulus: i64) -> i64 { if modulus == 1 { return 0; // Base case: any number modulo 1 is 0 } // Adjust if the exponent is negative by finding the modular inverse let mut base = if power < 0 { mod_inverse(base, modulus) } else { base % modulus }; let mut result = 1; // Initialize result power = power.abs(); // Work with the absolute value of the exponent // Perform the exponentiation while power > 0 { if power & 1 == 1 { result = (result * base) % modulus; } power >>= 1; // Divide the power by 2 base = (base * base) % modulus; // Square the base } result } #[cfg(test)] mod tests { use super::*; #[test] fn test_modular_exponential_positive() { assert_eq!(modular_exponential(2, 3, 5), 3); // 2^3 % 5 = 8 % 5 = 3 assert_eq!(modular_exponential(7, 2, 13), 10); // 7^2 % 13 = 49 % 13 = 10 assert_eq!(modular_exponential(5, 5, 31), 25); // 5^5 % 31 = 3125 % 31 = 25 assert_eq!(modular_exponential(10, 8, 11), 1); // 10^8 % 11 = 100000000 % 11 = 1 assert_eq!(modular_exponential(123, 45, 67), 62); // 123^45 % 67 } #[test] fn test_modular_inverse() { assert_eq!(mod_inverse(7, 13), 2); // Inverse of 7 mod 13 is 2 assert_eq!(mod_inverse(5, 31), 25); // Inverse of 5 mod 31 is 25 assert_eq!(mod_inverse(10, 11), 10); // Inverse of 10 mod 1 is 10 assert_eq!(mod_inverse(123, 67), 6); // Inverse of 123 mod 67 is 6 assert_eq!(mod_inverse(9, 17), 2); // Inverse of 9 mod 17 is 2 } #[test] fn test_modular_exponential_negative() { assert_eq!( modular_exponential(7, -2, 13), mod_inverse(7, 13).pow(2) % 13 ); // Inverse of 7 mod 13 is 2, 2^2 % 13 = 4 % 13 = 4 assert_eq!( modular_exponential(5, -5, 31), mod_inverse(5, 31).pow(5) % 31 ); // Inverse of 5 mod 31 is 25, 25^5 % 31 = 25 assert_eq!( modular_exponential(10, -8, 11), mod_inverse(10, 11).pow(8) % 11 ); // Inverse of 10 mod 11 is 10, 10^8 % 11 = 10 assert_eq!( modular_exponential(123, -5, 67), mod_inverse(123, 67).pow(5) % 67 ); // Inverse of 123 mod 67 is calculated via the function } #[test] fn test_modular_exponential_edge_cases() { assert_eq!(modular_exponential(0, 0, 1), 0); // 0^0 % 1 should be 0 as the modulus is 1 assert_eq!(modular_exponential(0, 10, 1), 0); // 0^n % 1 should be 0 for any n assert_eq!(modular_exponential(10, 0, 1), 0); // n^0 % 1 should be 0 for any n assert_eq!(modular_exponential(1, 1, 1), 0); // 1^1 % 1 should be 0 assert_eq!(modular_exponential(-1, 2, 1), 0); // (-1)^2 % 1 should be 0 } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/perfect_cube.rs
src/math/perfect_cube.rs
// Check if a number is a perfect cube using binary search. pub fn perfect_cube_binary_search(n: i64) -> bool { if n < 0 { return perfect_cube_binary_search(-n); } // Initialize left and right boundaries for binary search. let mut left = 0; let mut right = n.abs(); // Use the absolute value to handle negative numbers // Binary search loop to find the cube root. while left <= right { // Calculate the mid-point. let mid = left + (right - left) / 2; // Calculate the cube of the mid-point. let cube = mid * mid * mid; // Check if the cube equals the original number. match cube.cmp(&n) { std::cmp::Ordering::Equal => return true, std::cmp::Ordering::Less => left = mid + 1, std::cmp::Ordering::Greater => right = mid - 1, } } // If no cube root is found, return false. false } #[cfg(test)] mod tests { use super::*; macro_rules! test_perfect_cube { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let (n, expected) = $inputs; assert_eq!(perfect_cube_binary_search(n), expected); assert_eq!(perfect_cube_binary_search(-n), expected); } )* } } test_perfect_cube! { num_0_a_perfect_cube: (0, true), num_1_is_a_perfect_cube: (1, true), num_27_is_a_perfect_cube: (27, true), num_64_is_a_perfect_cube: (64, true), num_8_is_a_perfect_cube: (8, true), num_2_is_not_a_perfect_cube: (2, false), num_3_is_not_a_perfect_cube: (3, false), num_4_is_not_a_perfect_cube: (4, false), num_5_is_not_a_perfect_cube: (5, false), num_999_is_not_a_perfect_cube: (999, false), num_1000_is_a_perfect_cube: (1000, true), num_1001_is_not_a_perfect_cube: (1001, false), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/perfect_square.rs
src/math/perfect_square.rs
// Author : cyrixninja // Perfect Square : Checks if a number is perfect square number or not // https://en.wikipedia.org/wiki/Perfect_square pub fn perfect_square(num: i32) -> bool { if num < 0 { return false; } let sqrt_num = (num as f64).sqrt() as i32; sqrt_num * sqrt_num == num } pub fn perfect_square_binary_search(n: i32) -> bool { if n < 0 { return false; } let mut left = 0; let mut right = n; while left <= right { let mid = i32::midpoint(left, right); let mid_squared = mid * mid; match mid_squared.cmp(&n) { std::cmp::Ordering::Equal => return true, std::cmp::Ordering::Greater => right = mid - 1, std::cmp::Ordering::Less => left = mid + 1, } } false } #[cfg(test)] mod tests { use super::*; #[test] fn test_perfect_square() { assert!(perfect_square(9)); assert!(perfect_square(81)); assert!(perfect_square(4)); assert!(perfect_square(0)); assert!(!perfect_square(3)); assert!(!perfect_square(-19)); } #[test] fn test_perfect_square_binary_search() { assert!(perfect_square_binary_search(9)); assert!(perfect_square_binary_search(81)); assert!(perfect_square_binary_search(4)); assert!(perfect_square_binary_search(0)); assert!(!perfect_square_binary_search(3)); assert!(!perfect_square_binary_search(-19)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/sieve_of_eratosthenes.rs
src/math/sieve_of_eratosthenes.rs
/// Implements the Sieve of Eratosthenes algorithm to find all prime numbers up to a given limit. /// /// # Arguments /// /// * `num` - The upper limit up to which to find prime numbers (inclusive). /// /// # Returns /// /// A vector containing all prime numbers up to the specified limit. pub fn sieve_of_eratosthenes(num: usize) -> Vec<usize> { let mut result: Vec<usize> = Vec::new(); if num >= 2 { let mut sieve: Vec<bool> = vec![true; num + 1]; // 0 and 1 are not prime numbers sieve[0] = false; sieve[1] = false; let end: usize = (num as f64).sqrt() as usize; // Mark non-prime numbers in the sieve and collect primes up to `end` update_sieve(&mut sieve, end, num, &mut result); // Collect remaining primes beyond `end` result.extend(extract_remaining_primes(&sieve, end + 1)); } result } /// Marks non-prime numbers in the sieve and collects prime numbers up to `end`. /// /// # Arguments /// /// * `sieve` - A mutable slice of booleans representing the sieve. /// * `end` - The square root of the upper limit, used to optimize the algorithm. /// * `num` - The upper limit up to which to mark non-prime numbers. /// * `result` - A mutable vector to store the prime numbers. fn update_sieve(sieve: &mut [bool], end: usize, num: usize, result: &mut Vec<usize>) { for start in 2..=end { if sieve[start] { result.push(start); // Collect prime numbers up to `end` for i in (start * start..=num).step_by(start) { sieve[i] = false; } } } } /// Extracts remaining prime numbers from the sieve beyond the given start index. /// /// # Arguments /// /// * `sieve` - A slice of booleans representing the sieve with non-prime numbers marked as false. /// * `start` - The index to start checking for primes (inclusive). /// /// # Returns /// /// A vector containing all remaining prime numbers extracted from the sieve. fn extract_remaining_primes(sieve: &[bool], start: usize) -> Vec<usize> { sieve[start..] .iter() .enumerate() .filter_map(|(i, &is_prime)| if is_prime { Some(start + i) } else { None }) .collect() } #[cfg(test)] mod tests { use super::*; const PRIMES_UP_TO_997: [usize; 168] = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ]; macro_rules! sieve_tests { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let input: usize = $test_case; let expected: Vec<usize> = PRIMES_UP_TO_997.iter().cloned().filter(|&x| x <= input).collect(); assert_eq!(sieve_of_eratosthenes(input), expected); } )* } } sieve_tests! { test_0: 0, test_1: 1, test_2: 2, test_3: 3, test_4: 4, test_5: 5, test_6: 6, test_7: 7, test_11: 11, test_23: 23, test_24: 24, test_25: 25, test_26: 26, test_27: 27, test_28: 28, test_29: 29, test_33: 33, test_100: 100, test_997: 997, test_998: 998, test_999: 999, test_1000: 1000, } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/gaussian_error_linear_unit.rs
src/math/gaussian_error_linear_unit.rs
//! # Gaussian Error Linear Unit (GELU) Function //! //! The `gaussian_error_linear_unit` function computes the Gaussian Error Linear Unit (GELU) values of a given f64 number or a vector of f64 numbers. //! //! GELU is an activation function used in neural networks that introduces a smooth approximation of the rectifier function (ReLU). //! It is defined using the Gaussian cumulative distribution function and can help mitigate the vanishing gradient problem. //! //! ## Formula //! //! For a given input value `x`, the GELU function computes the output `y` as follows: //! //! `y = 0.5 * (1.0 + tanh(2.0 / sqrt(π) * (x + 0.044715 * x^3)))` //! //! Where `tanh` is the hyperbolic tangent function and `π` is the mathematical constant (approximately 3.14159). //! //! ## Gaussian Error Linear Unit (GELU) Function Implementation //! //! This implementation takes either a single f64 value or a reference to a vector of f64 values and returns the GELU transformation applied to each element. The input values are not altered. //! use std::f64::consts::E; use std::f64::consts::PI; fn tanh(vector: f64) -> f64 { (2. / (1. + E.powf(-2. * vector.to_owned()))) - 1. } pub fn gaussian_error_linear_unit(vector: &Vec<f64>) -> Vec<f64> { let mut gelu_vec = vector.to_owned(); for value in &mut gelu_vec { *value = *value * 0.5 * (1. + tanh(f64::powf(2. / PI, 0.5) * (*value + 0.044715 * value.powf(3.)))); } gelu_vec } #[cfg(test)] mod tests { use super::*; #[test] fn test_gaussian_error_linear_unit() { let test_vector = vec![-10., 2., -3., 4., -5., 10., 0.05]; assert_eq!( gaussian_error_linear_unit(&test_vector), vec![ -0.0, 1.9545976940877752, -0.0036373920817729943, 3.9999297540518075, -2.2917961972623857e-7, 10.0, 0.025996938238622008 ] ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/zellers_congruence_algorithm.rs
src/math/zellers_congruence_algorithm.rs
// returns the day of the week from the Gregorian Date pub fn zellers_congruence_algorithm(date: i32, month: i32, year: i32, as_string: bool) -> String { let q = date; let (m, y) = if month < 3 { (month + 12, year - 1) } else { (month, year) }; let day: i32 = (q + (26 * (m + 1) / 10) + (y % 100) + ((y % 100) / 4) + ((y / 100) / 4) + (5 * (y / 100))) % 7; if as_string { number_to_day(day) } else { day.to_string() } /* Note that the day follows the following guidelines: 0 = Saturday 1 = Sunday 2 = Monday 3 = Tuesday 4 = Wednesday 5 = Thursday 6 = Friday */ } fn number_to_day(number: i32) -> String { let days = [ "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", ]; String::from(days[number as usize]) } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(zellers_congruence_algorithm(25, 1, 2013, false), "6"); assert_eq!(zellers_congruence_algorithm(25, 1, 2013, true), "Friday"); assert_eq!(zellers_congruence_algorithm(16, 4, 2022, false), "0"); assert_eq!(zellers_congruence_algorithm(16, 4, 2022, true), "Saturday"); assert_eq!(zellers_congruence_algorithm(14, 12, 1978, false), "5"); assert_eq!(zellers_congruence_algorithm(15, 6, 2021, false), "3"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/softmax.rs
src/math/softmax.rs
//! # Softmax Function //! //! The `softmax` function computes the softmax values of a given array of f32 numbers. //! //! The softmax operation is often used in machine learning for converting a vector of real numbers into a //! probability distribution. It exponentiates each element in the input array, and then normalizes the //! results so that they sum to 1. //! //! ## Formula //! //! For a given input array `x`, the softmax function computes the output `y` as follows: //! //! `y_i = e^(x_i) / sum(e^(x_j) for all j)` //! //! ## Softmax Function Implementation //! //! This implementation uses the `std::f32::consts::E` constant for the base of the exponential function. and //! f32 vectors to compute the values. The function creates a new vector and not altering the input vector. //! use std::f32::consts::E; pub fn softmax(array: Vec<f32>) -> Vec<f32> { let mut softmax_array = array; for value in &mut softmax_array { *value = E.powf(*value); } let sum: f32 = softmax_array.iter().sum(); for value in &mut softmax_array { *value /= sum; } softmax_array } #[cfg(test)] mod tests { use super::*; #[test] fn test_softmax() { let test = vec![9.0, 0.5, -3.0, 0.0, 3.0]; assert_eq!( softmax(test), vec![ 0.9971961, 0.00020289792, 6.126987e-6, 0.00012306382, 0.0024718025 ] ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/square_root.rs
src/math/square_root.rs
/// squre_root returns the square root /// of a f64 number using Newton's method pub fn square_root(num: f64) -> f64 { if num < 0.0_f64 { return f64::NAN; } let mut root = 1.0_f64; while (root * root - num).abs() > 1e-10_f64 { root -= (root * root - num) / (2.0_f64 * root); } root } // fast_inv_sqrt returns an approximation of the inverse square root // This algorithm was first used in Quake and has been reimplemented in a few other languages // This crate implements it more thoroughly: https://docs.rs/quake-inverse-sqrt/latest/quake_inverse_sqrt/ pub fn fast_inv_sqrt(num: f32) -> f32 { // If you are confident in your input this can be removed for speed if num < 0.0f32 { return f32::NAN; } let i = num.to_bits(); let i = 0x5f3759df - (i >> 1); let y = f32::from_bits(i); println!("num: {:?}, out: {:?}", num, y * (1.5 - 0.5 * num * y * y)); // First iteration of Newton's approximation y * (1.5 - 0.5 * num * y * y) // The above can be repeated for more precision } #[cfg(test)] mod tests { use super::*; #[test] fn test_fast_inv_sqrt() { // Negatives don't have square roots: assert!(fast_inv_sqrt(-1.0f32).is_nan()); // Test a few cases, expect less than 1% error: let test_pairs = [(4.0, 0.5), (16.0, 0.25), (25.0, 0.2)]; for pair in test_pairs { assert!((fast_inv_sqrt(pair.0) - pair.1).abs() <= (0.01 * pair.0)); } } #[test] fn test_sqare_root() { assert!((square_root(4.0_f64) - 2.0_f64).abs() <= 1e-10_f64); assert!(square_root(-4.0_f64).is_nan()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/postfix_evaluation.rs
src/math/postfix_evaluation.rs
//! This module provides a function to evaluate postfix (Reverse Polish Notation) expressions. //! Postfix notation is a mathematical notation in which every operator follows all of its operands. //! //! The evaluator supports the four basic arithmetic operations: addition, subtraction, multiplication, and division. //! It handles errors such as division by zero, invalid operators, insufficient operands, and invalid postfix expressions. /// Enumeration of errors that can occur when evaluating a postfix expression. #[derive(Debug, PartialEq)] pub enum PostfixError { DivisionByZero, InvalidOperator, InsufficientOperands, InvalidExpression, } /// Evaluates a postfix expression and returns the result or an error. /// /// # Arguments /// /// * `expression` - A string slice that contains the postfix expression to be evaluated. /// The tokens (numbers and operators) should be separated by whitespace. /// /// # Returns /// /// * `Ok(isize)` if the expression is valid and evaluates to an integer. /// * `Err(PostfixError)` if the expression is invalid or encounters errors during evaluation. /// /// # Errors /// /// * `PostfixError::DivisionByZero` - If a division by zero is attempted. /// * `PostfixError::InvalidOperator` - If an unknown operator is encountered. /// * `PostfixError::InsufficientOperands` - If there are not enough operands for an operator. /// * `PostfixError::InvalidExpression` - If the expression is malformed (e.g., multiple values are left on the stack). pub fn evaluate_postfix(expression: &str) -> Result<isize, PostfixError> { let mut stack: Vec<isize> = Vec::new(); for token in expression.split_whitespace() { if let Ok(number) = token.parse::<isize>() { // If the token is a number, push it onto the stack. stack.push(number); } else { // If the token is an operator, pop the top two values from the stack, // apply the operator, and push the result back onto the stack. if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) { match token { "+" => stack.push(a + b), "-" => stack.push(a - b), "*" => stack.push(a * b), "/" => { if b == 0 { return Err(PostfixError::DivisionByZero); } stack.push(a / b); } _ => return Err(PostfixError::InvalidOperator), } } else { return Err(PostfixError::InsufficientOperands); } } } // The final result should be the only element on the stack. if stack.len() == 1 { Ok(stack[0]) } else { Err(PostfixError::InvalidExpression) } } #[cfg(test)] mod tests { use super::*; macro_rules! postfix_tests { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (input, expected) = $test_case; assert_eq!(evaluate_postfix(input), expected); } )* } } postfix_tests! { test_addition_of_two_numbers: ("2 3 +", Ok(5)), test_multiplication_and_addition: ("5 2 * 4 +", Ok(14)), test_simple_division: ("10 2 /", Ok(5)), test_operator_without_operands: ("+", Err(PostfixError::InsufficientOperands)), test_division_by_zero_error: ("5 0 /", Err(PostfixError::DivisionByZero)), test_invalid_operator_in_expression: ("2 3 #", Err(PostfixError::InvalidOperator)), test_missing_operator_for_expression: ("2 3", Err(PostfixError::InvalidExpression)), test_extra_operands_in_expression: ("2 3 4 +", Err(PostfixError::InvalidExpression)), test_empty_expression_error: ("", Err(PostfixError::InvalidExpression)), test_single_number_expression: ("42", Ok(42)), test_addition_of_negative_numbers: ("-3 -2 +", Ok(-5)), test_complex_expression_with_multiplication_and_addition: ("3 5 8 * 7 + *", Ok(141)), test_expression_with_extra_whitespace: (" 3 4 + ", Ok(7)), test_valid_then_invalid_operator: ("5 2 + 1 #", Err(PostfixError::InvalidOperator)), test_first_division_by_zero: ("5 0 / 6 0 /", Err(PostfixError::DivisionByZero)), test_complex_expression_with_multiple_operators: ("5 1 2 + 4 * + 3 -", Ok(14)), test_expression_with_only_whitespace: (" ", Err(PostfixError::InvalidExpression)), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/binomial_coefficient.rs
src/math/binomial_coefficient.rs
extern crate num_bigint; extern crate num_traits; use num_bigint::BigInt; use num_traits::FromPrimitive; /// Calculate binomial coefficient (n choose k). /// /// This function computes the binomial coefficient C(n, k) using BigInt /// for arbitrary precision arithmetic. /// /// Formula: /// C(n, k) = n! / (k! * (n - k)!) /// /// Reference: /// [Binomial Coefficient - Wikipedia](https://en.wikipedia.org/wiki/Binomial_coefficient) /// /// # Arguments /// /// * `n` - The total number of items. /// * `k` - The number of items to choose from `n`. /// /// # Returns /// /// Returns the binomial coefficient C(n, k) as a BigInt. pub fn binom(n: u64, k: u64) -> BigInt { let mut res = BigInt::from_u64(1).unwrap(); for i in 0..k { res = (res * BigInt::from_u64(n - i).unwrap()) / BigInt::from_u64(i + 1).unwrap(); } res } #[cfg(test)] mod tests { use super::*; #[test] fn test_binom_5_2() { assert_eq!(binom(5, 2), BigInt::from(10)); } #[test] fn test_binom_10_5() { assert_eq!(binom(10, 5), BigInt::from(252)); } #[test] fn test_binom_0_0() { assert_eq!(binom(0, 0), BigInt::from(1)); } #[test] fn test_binom_large_n_small_k() { assert_eq!(binom(1000, 2), BigInt::from(499500)); } #[test] fn test_binom_random_1() { // Random test case 1 assert_eq!(binom(7, 4), BigInt::from(35)); } #[test] fn test_binom_random_2() { // Random test case 2 assert_eq!(binom(12, 3), BigInt::from(220)); } #[test] fn test_binom_random_3() { // Random test case 3 assert_eq!(binom(20, 10), BigInt::from(184_756)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/area_of_polygon.rs
src/math/area_of_polygon.rs
/** * @file * @brief Calculate the area of a polygon defined by a vector of points. * * @details * This program provides a function to calculate the area of a polygon defined by a vector of points. * The area is calculated using the formula: A = |Σ((xi - xi-1) * (yi + yi-1))| / 2 * where (xi, yi) are the coordinates of the points in the vector. * * @param fig A vector of points defining the polygon. * @return The area of the polygon. * * @author [Gyandeep](https://github.com/Gyan172004) * @see [Wikipedia - Polygon](https://en.wikipedia.org/wiki/Polygon) */ pub struct Point { x: f64, y: f64, } /** * Calculate the area of a polygon defined by a vector of points. * @param fig A vector of points defining the polygon. * @return The area of the polygon. */ pub fn area_of_polygon(fig: &[Point]) -> f64 { let mut res = 0.0; for i in 0..fig.len() { let p = if i > 0 { &fig[i - 1] } else { &fig[fig.len() - 1] }; let q = &fig[i]; res += (p.x - q.x) * (p.y + q.y); } f64::abs(res) / 2.0 } #[cfg(test)] mod tests { use super::*; /** * Test case for calculating the area of a triangle. */ #[test] fn test_area_triangle() { let points = vec![ Point { x: 0.0, y: 0.0 }, Point { x: 1.0, y: 0.0 }, Point { x: 0.0, y: 1.0 }, ]; assert_eq!(area_of_polygon(&points), 0.5); } /** * Test case for calculating the area of a square. */ #[test] fn test_area_square() { let points = vec![ Point { x: 0.0, y: 0.0 }, Point { x: 1.0, y: 0.0 }, Point { x: 1.0, y: 1.0 }, Point { x: 0.0, y: 1.0 }, ]; assert_eq!(area_of_polygon(&points), 1.0); } /** * Test case for calculating the area of a hexagon. */ #[test] fn test_area_hexagon() { let points = vec![ Point { x: 0.0, y: 0.0 }, Point { x: 1.0, y: 0.0 }, Point { x: 1.5, y: 0.866 }, Point { x: 1.0, y: 1.732 }, Point { x: 0.0, y: 1.732 }, Point { x: -0.5, y: 0.866 }, ]; assert_eq!(area_of_polygon(&points), 2.598); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/factors.rs
src/math/factors.rs
/// Factors are natural numbers which can divide a given natural number to give a remainder of zero /// Hence 1, 2, 3 and 6 are all factors of 6, as they divide the number 6 completely, /// leaving no remainder. /// This function is to list out all the factors of a given number 'n' pub fn factors(number: u64) -> Vec<u64> { let mut factors: Vec<u64> = Vec::new(); for i in 1..=((number as f64).sqrt() as u64) { if number.is_multiple_of(i) { factors.push(i); if i != number / i { factors.push(number / i); } } } factors.sort(); factors } #[cfg(test)] mod tests { use super::*; #[test] fn prime_number() { assert_eq!(vec![1, 59], factors(59)); } #[test] fn highly_composite_number() { assert_eq!( vec![ 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, 360 ], factors(360) ); } #[test] fn composite_number() { assert_eq!(vec![1, 3, 23, 69], factors(69)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/extended_euclidean_algorithm.rs
src/math/extended_euclidean_algorithm.rs
fn update_step(a: &mut i32, old_a: &mut i32, quotient: i32) { let temp = *a; *a = *old_a - quotient * temp; *old_a = temp; } pub fn extended_euclidean_algorithm(a: i32, b: i32) -> (i32, i32, i32) { let (mut old_r, mut rem) = (a, b); let (mut old_s, mut coeff_s) = (1, 0); let (mut old_t, mut coeff_t) = (0, 1); while rem != 0 { let quotient = old_r / rem; update_step(&mut rem, &mut old_r, quotient); update_step(&mut coeff_s, &mut old_s, quotient); update_step(&mut coeff_t, &mut old_t, quotient); } (old_r, old_s, old_t) } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(extended_euclidean_algorithm(101, 13), (1, 4, -31)); assert_eq!(extended_euclidean_algorithm(123, 19), (1, -2, 13)); assert_eq!(extended_euclidean_algorithm(25, 36), (1, 13, -9)); assert_eq!(extended_euclidean_algorithm(69, 54), (3, -7, 9)); assert_eq!(extended_euclidean_algorithm(55, 79), (1, 23, -16)); assert_eq!(extended_euclidean_algorithm(33, 44), (11, -1, 1)); assert_eq!(extended_euclidean_algorithm(50, 70), (10, 3, -2)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/faster_perfect_numbers.rs
src/math/faster_perfect_numbers.rs
use super::{mersenne_primes::is_mersenne_prime, prime_numbers::prime_numbers}; use std::convert::TryInto; /* Generates a list of perfect numbers till `num` using the Lucas Lehmer test algorithm. url : https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test */ pub fn generate_perfect_numbers(num: usize) -> Vec<usize> { let mut results = Vec::new(); let prime_limit = get_prime_limit(num); for i in prime_numbers(prime_limit).iter() { let prime = *i; if is_mersenne_prime(prime) { results.push( (2_usize.pow(prime.try_into().unwrap()) - 1) * (2_usize.pow((prime - 1).try_into().unwrap())), ); } } results.into_iter().filter(|x| *x <= num).collect() } // Gets an approximate limit for the generate_perfect_numbers function fn get_prime_limit(num: usize) -> usize { (((num * 8 + 1) as f64).log2() as usize) / 2_usize } #[cfg(test)] mod tests { use super::*; #[test] fn perfect_numbers_till_n() { let n = 335564540; assert_eq!(generate_perfect_numbers(n), [6, 28, 496, 8128, 33550336]); assert_eq!(generate_perfect_numbers(40), [6, 28]); assert_eq!(generate_perfect_numbers(0), []); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/signum.rs
src/math/signum.rs
/// Signum function is a mathematical function that extracts /// the sign of a real number. It is also known as the sign function, /// and it is an odd piecewise function. /// If a number is negative, i.e. it is less than zero, then sgn(x) = -1 /// If a number is zero, then sgn(0) = 0 /// If a number is positive, i.e. it is greater than zero, then sgn(x) = 1 pub fn signum(number: f64) -> i8 { if number == 0.0 { return 0; } else if number > 0.0 { return 1; } -1 } #[cfg(test)] mod tests { use super::*; #[test] fn positive_integer() { assert_eq!(signum(15.0), 1); } #[test] fn negative_integer() { assert_eq!(signum(-30.0), -1); } #[test] fn zero() { assert_eq!(signum(0.0), 0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/sum_of_harmonic_series.rs
src/math/sum_of_harmonic_series.rs
// Author : cyrixninja // Sum of Harmonic Series : Find the sum of n terms in an harmonic progression. The calculation starts with the // first_term and loops adding the common difference of Arithmetic Progression by which // the given Harmonic Progression is linked. // Wikipedia Reference : https://en.wikipedia.org/wiki/Interquartile_range // Other References : https://the-algorithms.com/algorithm/sum-of-harmonic-series?lang=python pub fn sum_of_harmonic_progression( first_term: f64, common_difference: f64, number_of_terms: i32, ) -> f64 { let mut arithmetic_progression = vec![1.0 / first_term]; let mut current_term = 1.0 / first_term; for _ in 0..(number_of_terms - 1) { current_term += common_difference; arithmetic_progression.push(current_term); } let harmonic_series: Vec<f64> = arithmetic_progression .into_iter() .map(|step| 1.0 / step) .collect(); harmonic_series.iter().sum() } #[cfg(test)] mod tests { use super::*; #[test] fn test_sum_of_harmonic_progression() { assert_eq!(sum_of_harmonic_progression(1.0 / 2.0, 2.0, 2), 0.75); assert_eq!( sum_of_harmonic_progression(1.0 / 5.0, 5.0, 5), 0.45666666666666667 ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/baby_step_giant_step.rs
src/math/baby_step_giant_step.rs
use crate::math::greatest_common_divisor; /// Baby-step Giant-step algorithm /// /// Solving discrete logarithm problem: /// a^x = b (mod n) , with respect to gcd(a, n) == 1 /// with O(sqrt(n)) time complexity. /// /// Wikipedia reference: https://en.wikipedia.org/wiki/Baby-step_giant-step /// When a is the primitive root modulo n, the answer is unique. /// Otherwise it will return the smallest positive solution use std::collections::HashMap; pub fn baby_step_giant_step(a: usize, b: usize, n: usize) -> Option<usize> { if greatest_common_divisor::greatest_common_divisor_stein(a as u64, n as u64) != 1 { return None; } let mut h_map = HashMap::new(); let m = (n as f64).sqrt().ceil() as usize; // baby step let mut step = 1; for i in 0..m { h_map.insert((step * b) % n, i); step = (step * a) % n; } // Now step = a^m (mod n), giant step let giant_step = step; for i in (m..=n).step_by(m) { if let Some(v) = h_map.get(&step) { return Some(i - v); } step = (step * giant_step) % n; } None } #[cfg(test)] mod tests { use super::baby_step_giant_step; #[test] fn small_numbers() { assert_eq!(baby_step_giant_step(5, 3, 11), Some(2)); assert_eq!(baby_step_giant_step(3, 83, 100), Some(9)); assert_eq!(baby_step_giant_step(9, 1, 61), Some(5)); assert_eq!(baby_step_giant_step(5, 1, 67), Some(22)); assert_eq!(baby_step_giant_step(7, 1, 45), Some(12)); } #[test] fn primitive_root_tests() { assert_eq!( baby_step_giant_step(3, 311401496, 998244353), Some(178105253) ); assert_eq!( baby_step_giant_step(5, 324637211, 1000000007), Some(976653449) ); } #[test] fn random_numbers() { assert_eq!(baby_step_giant_step(174857, 48604, 150991), Some(177)); assert_eq!(baby_step_giant_step(912103, 53821, 75401), Some(2644)); assert_eq!(baby_step_giant_step(448447, 365819, 671851), Some(23242)); assert_eq!( baby_step_giant_step(220757103, 92430653, 434948279), Some(862704) ); assert_eq!( baby_step_giant_step(176908456, 23538399, 142357679), Some(14215560) ); } #[test] fn no_solution() { assert!(baby_step_giant_step(7, 6, 45).is_none()); assert!(baby_step_giant_step(23, 15, 85).is_none()); assert!(baby_step_giant_step(2, 1, 84).is_none()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/area_under_curve.rs
src/math/area_under_curve.rs
pub fn area_under_curve(start: f64, end: f64, func: fn(f64) -> f64, step_count: usize) -> f64 { assert!(step_count > 0); let (start, end) = if start > end { (end, start) } else { (start, end) }; //swap if bounds reversed let step_length: f64 = (end - start) / step_count as f64; let mut area = 0f64; let mut fx1 = func(start); let mut fx2: f64; for eval_point in (1..=step_count).map(|x| (x as f64 * step_length) + start) { fx2 = func(eval_point); area += (fx2 + fx1).abs() * step_length * 0.5; fx1 = fx2; } area } #[cfg(test)] mod test { use super::*; #[test] fn test_linear_func() { assert_eq!(area_under_curve(1f64, 2f64, |x| x, 10), 1.5000000000000002); } #[test] fn test_quadratic_func() { assert_eq!( area_under_curve(1f64, 2f64, |x| x * x, 1000), 2.333333500000005 ); } #[test] fn test_zero_length() { assert_eq!(area_under_curve(0f64, 0f64, |x| x * x, 1000), 0.0); } #[test] fn test_reverse() { assert_eq!( area_under_curve(1f64, 2f64, |x| x, 10), area_under_curve(2f64, 1f64, |x| x, 10) ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/trial_division.rs
src/math/trial_division.rs
fn floor(value: f64, scale: u8) -> f64 { let multiplier = 10i64.pow(scale as u32) as f64; (value * multiplier).floor() } fn double_to_int(amount: f64) -> i128 { amount.round() as i128 } pub fn trial_division(mut num: i128) -> Vec<i128> { if num < 0 { return trial_division(-num); } let mut result: Vec<i128> = vec![]; if num == 0 { return result; } while num % 2 == 0 { result.push(2); num /= 2; num = double_to_int(floor(num as f64, 0)) } let mut f: i128 = 3; while f.pow(2) <= num { if num % f == 0 { result.push(f); num /= f; num = double_to_int(floor(num as f64, 0)) } else { f += 2 } } if num != 1 { result.push(num) } result } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(trial_division(0), vec![]); assert_eq!(trial_division(1), vec![]); assert_eq!(trial_division(9), vec!(3, 3)); assert_eq!(trial_division(-9), vec!(3, 3)); assert_eq!(trial_division(10), vec!(2, 5)); assert_eq!(trial_division(11), vec!(11)); assert_eq!(trial_division(33), vec!(3, 11)); assert_eq!(trial_division(2003), vec!(2003)); assert_eq!(trial_division(100001), vec!(11, 9091)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/euclidean_distance.rs
src/math/euclidean_distance.rs
// Author : cyrixninja // Calculate the Euclidean distance between two vectors // Wikipedia : https://en.wikipedia.org/wiki/Euclidean_distance pub fn euclidean_distance(vector_1: &Vector, vector_2: &Vector) -> f64 { // Calculate the Euclidean distance using the provided vectors. let squared_sum: f64 = vector_1 .iter() .zip(vector_2.iter()) .map(|(&a, &b)| (a - b).powi(2)) .sum(); squared_sum.sqrt() } type Vector = Vec<f64>; #[cfg(test)] mod tests { use super::*; // Define a test function for the euclidean_distance function. #[test] fn test_euclidean_distance() { // First test case: 2D vectors let vec1_2d = vec![1.0, 2.0]; let vec2_2d = vec![4.0, 6.0]; // Calculate the Euclidean distance let result_2d = euclidean_distance(&vec1_2d, &vec2_2d); assert_eq!(result_2d, 5.0); // Second test case: 4D vectors let vec1_4d = vec![1.0, 2.0, 3.0, 4.0]; let vec2_4d = vec![5.0, 6.0, 7.0, 8.0]; // Calculate the Euclidean distance let result_4d = euclidean_distance(&vec1_4d, &vec2_4d); assert_eq!(result_4d, 8.0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/interest.rs
src/math/interest.rs
// value of e use std::f64::consts::E; // function to calculate simple interest pub fn simple_interest(principal: f64, annual_rate: f64, years: f64) -> (f64, f64) { let interest = principal * annual_rate * years; let value = principal * (1.0 + (annual_rate * years)); println!("Interest earned: {interest}"); println!("Future value: {value}"); (interest, value) } // function to calculate compound interest compounded over periods or continuously pub fn compound_interest(principal: f64, annual_rate: f64, years: f64, period: Option<f64>) -> f64 { // checks if the period is None type, if so calculates continuous compounding interest let value = if period.is_none() { principal * E.powf(annual_rate * years) } else { // unwraps the option type or defaults to 0 if None type and assigns it to prim_period let prim_period: f64 = period.unwrap_or(0.0); // checks if the period is less than or equal to zero if prim_period <= 0.0_f64 { return f64::NAN; } principal * (1.0 + (annual_rate / prim_period).powf(prim_period * years)) }; println!("Future value: {value}"); value } #[cfg(test)] mod tests { use super::*; #[test] fn test_simple() { let x = 385.65_f64 * 0.03_f64 * 5.0_f64; let y = 385.65_f64 * (1.0 + (0.03_f64 * 5.0_f64)); assert_eq!(simple_interest(385.65_f64, 0.03_f64, 5.0_f64), (x, y)); } #[test] fn test_compounding() { let x = 385.65_f64 * E.powf(0.03_f64 * 5.0_f64); assert_eq!(compound_interest(385.65_f64, 0.03_f64, 5.0_f64, None), x); let y = 385.65_f64 * (1.0 + (0.03_f64 / 5.0_f64).powf(5.0_f64 * 5.0_f64)); assert_eq!( compound_interest(385.65_f64, 0.03_f64, 5.0_f64, Some(5.0_f64)), y ); assert!(compound_interest(385.65_f64, 0.03_f64, 5.0_f64, Some(-5.0_f64)).is_nan()); assert!(compound_interest(385.65_f64, 0.03_f64, 5.0_f64, Some(0.0_f64)).is_nan()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/tanh.rs
src/math/tanh.rs
//Rust implementation of the Tanh (hyperbolic tangent) activation function. //The formula for Tanh: (e^x - e^(-x))/(e^x + e^(-x)) OR (2/(1+e^(-2x))-1 //More information on the concepts of Sigmoid can be found here: //https://en.wikipedia.org/wiki/Hyperbolic_functions //The function below takes a reference to a mutable <f32> Vector as an argument //and returns the vector with 'Tanh' applied to all values. //Of course, these functions can be changed by the developer so that the input vector isn't manipulated. //This is simply an implemenation of the formula. use std::f32::consts::E; pub fn tanh(array: &mut Vec<f32>) -> &mut Vec<f32> { //note that these calculations are assuming the Vector values consists of real numbers in radians for value in &mut *array { *value = (2. / (1. + E.powf(-2. * *value))) - 1.; } array } #[cfg(test)] mod tests { use super::*; #[test] fn test_tanh() { let mut test = Vec::from([1.0, 0.5, -1.0, 0.0, 0.3]); assert_eq!( tanh(&mut test), &mut Vec::<f32>::from([0.76159406, 0.4621172, -0.7615941, 0.0, 0.29131258,]) ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/matrix_ops.rs
src/math/matrix_ops.rs
// Basic matrix operations using a Matrix type with internally uses // a vector representation to store matrix elements. // Generic using the MatrixElement trait, which can be implemented with // the matrix_element_type_def macro. // Wikipedia reference: https://www.wikiwand.com/en/Matrix_(mathematics) use std::ops::{Add, AddAssign, Index, IndexMut, Mul, Sub}; // Define macro to build a matrix idiomatically #[macro_export] macro_rules! matrix { [$([$($x:expr),* $(,)*]),* $(,)*] => {{ Matrix::from(vec![$(vec![$($x,)*],)*]) }}; } // Define a trait "alias" for suitable matrix elements pub trait MatrixElement: Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + AddAssign + Copy + From<u8> { } // Define a macro to implement the MatrixElement trait for desired types #[macro_export] macro_rules! matrix_element_type_def { ($T: ty) => { // Implement trait for type impl MatrixElement for $T {} // Defining left-hand multiplication in this form // prevents errors for uncovered types impl Mul<&Matrix<$T>> for $T { type Output = Matrix<$T>; fn mul(self, rhs: &Matrix<$T>) -> Self::Output { rhs * self } } }; ($T: ty, $($Ti: ty),+) => { // Decompose type definitions recursively matrix_element_type_def!($T); matrix_element_type_def!($($Ti),+); }; } matrix_element_type_def!(i16, i32, i64, i128, u8, u16, u32, u128, f32, f64); #[derive(PartialEq, Eq, Debug)] pub struct Matrix<T: MatrixElement> { data: Vec<T>, rows: usize, cols: usize, } impl<T: MatrixElement> Matrix<T> { pub fn new(data: Vec<T>, rows: usize, cols: usize) -> Self { // Build a matrix from the internal vector representation if data.len() != rows * cols { panic!("Inconsistent data and dimensions combination for matrix") } Matrix { data, rows, cols } } pub fn zero(rows: usize, cols: usize) -> Self { // Build a matrix of zeros Matrix { data: vec![0.into(); rows * cols], rows, cols, } } pub fn identity(len: usize) -> Self { // Build an identity matrix let mut identity = Matrix::zero(len, len); // Diagonal of ones for i in 0..len { identity[[i, i]] = 1.into(); } identity } pub fn transpose(&self) -> Self { // Transpose a matrix of any size let mut result = Matrix::zero(self.cols, self.rows); for i in 0..self.rows { for j in 0..self.cols { result[[i, j]] = self[[j, i]]; } } result } } impl<T: MatrixElement> Index<[usize; 2]> for Matrix<T> { type Output = T; fn index(&self, index: [usize; 2]) -> &Self::Output { let [i, j] = index; if i >= self.rows || j >= self.cols { panic!("Matrix index out of bounds"); } &self.data[(self.cols * i) + j] } } impl<T: MatrixElement> IndexMut<[usize; 2]> for Matrix<T> { fn index_mut(&mut self, index: [usize; 2]) -> &mut Self::Output { let [i, j] = index; if i >= self.rows || j >= self.cols { panic!("Matrix index out of bounds"); } &mut self.data[(self.cols * i) + j] } } impl<T: MatrixElement> Add<&Matrix<T>> for &Matrix<T> { type Output = Matrix<T>; fn add(self, rhs: &Matrix<T>) -> Self::Output { // Add two matrices. They need to have identical dimensions. if self.rows != rhs.rows || self.cols != rhs.cols { panic!("Matrix dimensions do not match"); } let mut result = Matrix::zero(self.rows, self.cols); for i in 0..self.rows { for j in 0..self.cols { result[[i, j]] = self[[i, j]] + rhs[[i, j]]; } } result } } impl<T: MatrixElement> Sub for &Matrix<T> { type Output = Matrix<T>; fn sub(self, rhs: Self) -> Self::Output { // Subtract one matrix from another. They need to have identical dimensions. if self.rows != rhs.rows || self.cols != rhs.cols { panic!("Matrix dimensions do not match"); } let mut result = Matrix::zero(self.rows, self.cols); for i in 0..self.rows { for j in 0..self.cols { result[[i, j]] = self[[i, j]] - rhs[[i, j]]; } } result } } impl<T: MatrixElement> Mul for &Matrix<T> { type Output = Matrix<T>; fn mul(self, rhs: Self) -> Self::Output { // Multiply two matrices. The multiplier needs to have the same amount // of columns as the multiplicand has rows. if self.cols != rhs.rows { panic!("Matrix dimensions do not match"); } let mut result = Matrix::zero(self.rows, rhs.cols); for i in 0..self.rows { for j in 0..rhs.cols { result[[i, j]] = { let mut sum = 0.into(); for k in 0..self.cols { sum += self[[i, k]] * rhs[[k, j]]; } sum }; } } result } } impl<T: MatrixElement> Mul<T> for &Matrix<T> { type Output = Matrix<T>; fn mul(self, rhs: T) -> Self::Output { // Multiply a matrix of any size with a scalar let mut result = Matrix::zero(self.rows, self.cols); for i in 0..self.rows { for j in 0..self.cols { result[[i, j]] = rhs * self[[i, j]]; } } result } } impl<T: MatrixElement> From<Vec<Vec<T>>> for Matrix<T> { fn from(v: Vec<Vec<T>>) -> Self { let rows = v.len(); let cols = v.first().map_or(0, |row| row.len()); // Ensure consistent dimensions for row in v.iter().skip(1) { if row.len() != cols { panic!("Invalid matrix dimensions. Columns must be consistent."); } } if rows != 0 && cols == 0 { panic!("Invalid matrix dimensions. Multiple empty rows"); } let data = v.into_iter().flat_map(|row| row.into_iter()).collect(); Self::new(data, rows, cols) } } #[cfg(test)] // rustfmt skipped to prevent unformatting matrix definitions to a single line #[rustfmt::skip] mod tests { use super::Matrix; use std::panic; const DELTA: f64 = 1e-3; macro_rules! assert_f64_eq { ($a:expr, $b:expr) => { assert_eq!($a.data.len(), $b.data.len()); if !$a .data .iter() .zip($b.data.iter()) .all(|(x, y)| (*x as f64 - *y as f64).abs() < DELTA) { panic!(); } }; } #[test] fn test_invalid_matrix() { let result = panic::catch_unwind(|| matrix![ [1, 0, 0, 4], [0, 1, 0], [0, 0, 1], ]); assert!(result.is_err()); } #[test] fn test_empty_matrix() { let a: Matrix<i32> = matrix![]; let result = panic::catch_unwind(|| a[[0, 0]]); assert!(result.is_err()); } #[test] fn test_zero_matrix() { let a: Matrix<f64> = Matrix::zero(3, 5); let z = matrix![ [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], ]; assert_f64_eq!(a, z); } #[test] fn test_identity_matrix() { let a: Matrix<f64> = Matrix::identity(5); let id = matrix![ [1.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0], ]; assert_f64_eq!(a, id); } #[test] fn test_invalid_add() { let a = matrix![ [1, 0, 1], [0, 2, 0], [5, 0, 1] ]; let err = matrix![ [1, 2], [2, 4], ]; let result = panic::catch_unwind(|| &a + &err); assert!(result.is_err()); } #[test] fn test_add_i32() { let a = matrix![ [1, 0, 1], [0, 2, 0], [5, 0, 1] ]; let b = matrix![ [1, 0, 0], [0, 1, 0], [0, 0, 1], ]; let add = matrix![ [2, 0, 1], [0, 3, 0], [5, 0, 2], ]; assert_eq!(&a + &b, add); } #[test] fn test_add_f64() { let a = matrix![ [1.0, 2.0, 1.0], [3.0, 2.0, 0.0], [5.0, 0.0, 1.0], ]; let b = matrix![ [1.0, 10.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], ]; let add = matrix![ [2.0, 12.0, 1.0], [3.0, 3.0, 0.0], [5.0, 0.0, 2.0], ]; assert_f64_eq!(&a + &b, add); } #[test] fn test_invalid_sub() { let a = matrix![ [2, 3], [10, 2], ]; let err = matrix![ [5, 6, 10], [7, 2, 2], [12, 0, 1], ]; let result = panic::catch_unwind(|| &a - &err); assert!(result.is_err()); } #[test] fn test_subtract_i32() { let a = matrix![ [1, 0, 1], [0, 2, 0], [5, 0, 1], ]; let b = matrix![ [1, 0, 0], [0, 1, 3], [0, 0, 1], ]; let sub = matrix![ [0, 0, 1], [0, 1, -3], [5, 0, 0], ]; assert_eq!(&a - &b, sub); } #[test] fn test_subtract_f64() { let a = matrix![ [7.0, 2.0, 1.0], [0.0, 3.0, 2.0], [5.3, 8.8, std::f64::consts::PI], ]; let b = matrix![ [1.0, 0.0, 5.0], [-2.0, 1.0, 3.0], [0.0, 2.2, std::f64::consts::PI], ]; let sub = matrix![ [6.0, 2.0, -4.0], [2.0, 2.0, -1.0], [5.3, 6.6, 0.0], ]; assert_f64_eq!(&a - &b, sub); } #[test] fn test_invalid_mul() { let a = matrix![ [1, 2, 3], [4, 2, 6], [3, 4, 1], [2, 4, 8], ]; let err = matrix![ [1, 3, 3, 2], [7, 6, 2, 1], [3, 4, 2, 1], [3, 4, 2, 1], ]; let result = panic::catch_unwind(|| &a * &err); assert!(result.is_err()); } #[test] fn test_mul_i32() { let a = matrix![ [1, 2, 3], [4, 2, 6], [3, 4, 1], [2, 4, 8], ]; let b = matrix![ [1, 3, 3, 2], [7, 6, 2, 1], [3, 4, 2, 1], ]; let mul = matrix![ [24, 27, 13, 7], [36, 48, 28, 16], [34, 37, 19, 11], [54, 62, 30, 16], ]; assert_eq!(&a * &b, mul); } #[test] fn test_mul_f64() { let a = matrix![ [5.5, 2.9, 1.13, 9.0], [0.0, 3.0, 11.0, 17.2], [5.3, 8.8, 2.76, 3.3], ]; let b = matrix![ [1.0, 0.3, 5.0], [-2.0, 1.0, 3.0], [-3.6, 1.5, 3.0], [0.0, 2.2, 2.0], ]; let mul = matrix![ [-4.368, 26.045, 57.59], [-45.6, 57.34, 76.4], [-22.236, 21.79, 67.78], ]; assert_f64_eq!(&a * &b, mul); } #[test] fn test_transpose_i32() { let a = matrix![ [1, 0, 1], [0, 2, 0], [5, 0, 1], ]; let t = matrix![ [1, 0, 5], [0, 2, 0], [1, 0, 1], ]; assert_eq!(a.transpose(), t); } #[test] fn test_transpose_f64() { let a = matrix![ [3.0, 4.0, 2.0], [0.0, 1.0, 3.0], [3.0, 1.0, 1.0], ]; let t = matrix![ [3.0, 0.0, 3.0], [4.0, 1.0, 1.0], [2.0, 3.0, 1.0], ]; assert_eq!(a.transpose(), t); } #[test] fn test_matrix_scalar_zero_mul() { let a = matrix![ [3, 2, 2], [0, 2, 0], [5, 4, 1], ]; let scalar = 0; let scalar_mul = Matrix::zero(3, 3); assert_eq!(scalar * &a, scalar_mul); } #[test] fn test_matrix_scalar_mul_i32() { let a = matrix![ [3, 2, 2], [0, 2, 0], [5, 4, 1], ]; let scalar = 3; let scalar_mul = matrix![ [9, 6, 6], [0, 6, 0], [15, 12, 3], ]; assert_eq!(scalar * &a, scalar_mul); } #[test] fn test_matrix_scalar_mul_f64() { let a = matrix![ [3.2, 5.5, 9.2], [1.1, 0.0, 2.3], [0.3, 4.2, 0.0], ]; let scalar = 1.5_f64; let scalar_mul = matrix![ [4.8, 8.25, 13.8], [1.65, 0.0, 3.45], [0.45, 6.3, 0.0], ]; assert_f64_eq!(scalar * &a, scalar_mul); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/catalan_numbers.rs
src/math/catalan_numbers.rs
// Introduction to Catalan Numbers: // Catalan numbers are a sequence of natural numbers with many applications in combinatorial mathematics. // They are named after the Belgian mathematician Eugène Charles Catalan, who contributed to their study. // Catalan numbers appear in various combinatorial problems, including counting correct bracket sequences, // full binary trees, triangulations of polygons, and more. // For more information, refer to the Wikipedia page on Catalan numbers: // https://en.wikipedia.org/wiki/Catalan_number // Author: [Gyandeep] (https://github.com/Gyan172004) const MOD: i64 = 1000000007; // Define your MOD value here const MAX: usize = 1005; // Define your MAX value here pub fn init_catalan() -> Vec<i64> { let mut catalan = vec![0; MAX]; catalan[0] = 1; catalan[1] = 1; for i in 2..MAX { catalan[i] = 0; for j in 0..i { catalan[i] += (catalan[j] * catalan[i - j - 1]) % MOD; if catalan[i] >= MOD { catalan[i] -= MOD; } } } catalan } #[cfg(test)] mod tests { use super::*; #[test] fn test_catalan() { let catalan = init_catalan(); // Test case 1: Catalan number for n = 0 assert_eq!(catalan[0], 1); // Test case 2: Catalan number for n = 1 assert_eq!(catalan[1], 1); // Test case 3: Catalan number for n = 5 assert_eq!(catalan[5], 42); // Test case 4: Catalan number for n = 10 assert_eq!(catalan[10], 16796); // Test case 5: Catalan number for n = 15 assert_eq!(catalan[15], 9694845); // Print a success message if all tests pass println!("All tests passed!"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/greatest_common_divisor.rs
src/math/greatest_common_divisor.rs
/// Greatest Common Divisor. /// /// greatest_common_divisor(num1, num2) returns the greatest number of num1 and num2. /// /// Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor /// gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility use std::cmp::{max, min}; pub fn greatest_common_divisor_recursive(a: i64, b: i64) -> i64 { if a == 0 { b.abs() } else { greatest_common_divisor_recursive(b % a, a) } } pub fn greatest_common_divisor_iterative(mut a: i64, mut b: i64) -> i64 { while a != 0 { let remainder = b % a; b = a; a = remainder; } b.abs() } pub fn greatest_common_divisor_stein(a: u64, b: u64) -> u64 { match ((a, b), (a & 1, b & 1)) { // gcd(x, x) = x ((x, y), _) if x == y => y, // gcd(x, 0) = gcd(0, x) = x ((0, x), _) | ((x, 0), _) => x, // gcd(x, y) = gcd(x / 2, y) if x is even and y is odd // gcd(x, y) = gcd(x, y / 2) if y is even and x is odd ((x, y), (0, 1)) | ((y, x), (1, 0)) => greatest_common_divisor_stein(x >> 1, y), // gcd(x, y) = 2 * gcd(x / 2, y / 2) if x and y are both even ((x, y), (0, 0)) => greatest_common_divisor_stein(x >> 1, y >> 1) << 1, // if x and y are both odd ((x, y), (1, 1)) => { // then gcd(x, y) = gcd((x - y) / 2, y) if x >= y // gcd(x, y) = gcd((y - x) / 2, x) otherwise let (x, y) = (min(x, y), max(x, y)); greatest_common_divisor_stein((y - x) >> 1, x) } _ => unreachable!(), } } #[cfg(test)] mod tests { use super::*; #[test] fn positive_number_recursive() { assert_eq!(greatest_common_divisor_recursive(4, 16), 4); assert_eq!(greatest_common_divisor_recursive(16, 4), 4); assert_eq!(greatest_common_divisor_recursive(3, 5), 1); assert_eq!(greatest_common_divisor_recursive(40, 40), 40); assert_eq!(greatest_common_divisor_recursive(27, 12), 3); } #[test] fn positive_number_iterative() { assert_eq!(greatest_common_divisor_iterative(4, 16), 4); assert_eq!(greatest_common_divisor_iterative(16, 4), 4); assert_eq!(greatest_common_divisor_iterative(3, 5), 1); assert_eq!(greatest_common_divisor_iterative(40, 40), 40); assert_eq!(greatest_common_divisor_iterative(27, 12), 3); } #[test] fn positive_number_stein() { assert_eq!(greatest_common_divisor_stein(4, 16), 4); assert_eq!(greatest_common_divisor_stein(16, 4), 4); assert_eq!(greatest_common_divisor_stein(3, 5), 1); assert_eq!(greatest_common_divisor_stein(40, 40), 40); assert_eq!(greatest_common_divisor_stein(27, 12), 3); } #[test] fn negative_number_recursive() { assert_eq!(greatest_common_divisor_recursive(-32, -8), 8); assert_eq!(greatest_common_divisor_recursive(-8, -32), 8); assert_eq!(greatest_common_divisor_recursive(-3, -5), 1); assert_eq!(greatest_common_divisor_recursive(-40, -40), 40); assert_eq!(greatest_common_divisor_recursive(-12, -27), 3); } #[test] fn negative_number_iterative() { assert_eq!(greatest_common_divisor_iterative(-32, -8), 8); assert_eq!(greatest_common_divisor_iterative(-8, -32), 8); assert_eq!(greatest_common_divisor_iterative(-3, -5), 1); assert_eq!(greatest_common_divisor_iterative(-40, -40), 40); assert_eq!(greatest_common_divisor_iterative(-12, -27), 3); } #[test] fn mix_recursive() { assert_eq!(greatest_common_divisor_recursive(0, -5), 5); assert_eq!(greatest_common_divisor_recursive(-5, 0), 5); assert_eq!(greatest_common_divisor_recursive(-64, 32), 32); assert_eq!(greatest_common_divisor_recursive(-32, 64), 32); assert_eq!(greatest_common_divisor_recursive(-40, 40), 40); assert_eq!(greatest_common_divisor_recursive(12, -27), 3); } #[test] fn mix_iterative() { assert_eq!(greatest_common_divisor_iterative(0, -5), 5); assert_eq!(greatest_common_divisor_iterative(-5, 0), 5); assert_eq!(greatest_common_divisor_iterative(-64, 32), 32); assert_eq!(greatest_common_divisor_iterative(-32, 64), 32); assert_eq!(greatest_common_divisor_iterative(-40, 40), 40); assert_eq!(greatest_common_divisor_iterative(12, -27), 3); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/prime_numbers.rs
src/math/prime_numbers.rs
pub fn prime_numbers(max: usize) -> Vec<usize> { let mut result: Vec<usize> = Vec::new(); if max >= 2 { result.push(2) } for i in (3..=max).step_by(2) { let stop: usize = (i as f64).sqrt() as usize + 1; let mut status = true; for j in (3..stop).step_by(2) { if i % j == 0 { status = false; break; } } if status { result.push(i) } } result } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(prime_numbers(0), vec![]); assert_eq!(prime_numbers(11), vec![2, 3, 5, 7, 11]); assert_eq!(prime_numbers(25), vec![2, 3, 5, 7, 11, 13, 17, 19, 23]); assert_eq!( prime_numbers(33), vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/mod.rs
src/math/mod.rs
mod abs; mod aliquot_sum; mod amicable_numbers; mod area_of_polygon; mod area_under_curve; mod armstrong_number; mod average; mod baby_step_giant_step; mod bell_numbers; mod binary_exponentiation; mod binomial_coefficient; mod catalan_numbers; mod ceil; mod chinese_remainder_theorem; mod collatz_sequence; mod combinations; mod cross_entropy_loss; mod decimal_to_fraction; mod doomsday; mod elliptic_curve; mod euclidean_distance; mod exponential_linear_unit; mod extended_euclidean_algorithm; pub mod factorial; mod factors; mod fast_fourier_transform; mod fast_power; mod faster_perfect_numbers; mod field; mod frizzy_number; mod gaussian_elimination; mod gaussian_error_linear_unit; mod gcd_of_n_numbers; mod geometric_series; mod greatest_common_divisor; mod huber_loss; mod infix_to_postfix; mod interest; mod interpolation; mod interquartile_range; mod karatsuba_multiplication; mod lcm_of_n_numbers; mod leaky_relu; mod least_square_approx; mod linear_sieve; mod logarithm; mod lucas_series; mod matrix_ops; mod mersenne_primes; mod miller_rabin; mod modular_exponential; mod newton_raphson; mod nthprime; mod pascal_triangle; mod perfect_cube; mod perfect_numbers; mod perfect_square; mod pollard_rho; mod postfix_evaluation; mod prime_check; mod prime_factors; mod prime_numbers; mod quadratic_residue; mod random; mod relu; mod sieve_of_eratosthenes; mod sigmoid; mod signum; mod simpsons_integration; mod softmax; mod sprague_grundy_theorem; mod square_pyramidal_numbers; mod square_root; mod sum_of_digits; mod sum_of_geometric_progression; mod sum_of_harmonic_series; mod sylvester_sequence; mod tanh; mod trapezoidal_integration; mod trial_division; mod trig_functions; mod vector_cross_product; mod zellers_congruence_algorithm; pub use self::abs::abs; pub use self::aliquot_sum::aliquot_sum; pub use self::amicable_numbers::amicable_pairs_under_n; pub use self::area_of_polygon::area_of_polygon; pub use self::area_under_curve::area_under_curve; pub use self::armstrong_number::is_armstrong_number; pub use self::average::{mean, median, mode}; pub use self::baby_step_giant_step::baby_step_giant_step; pub use self::bell_numbers::bell_number; pub use self::binary_exponentiation::binary_exponentiation; pub use self::binomial_coefficient::binom; pub use self::catalan_numbers::init_catalan; pub use self::ceil::ceil; pub use self::chinese_remainder_theorem::chinese_remainder_theorem; pub use self::collatz_sequence::sequence; pub use self::combinations::combinations; pub use self::cross_entropy_loss::cross_entropy_loss; pub use self::decimal_to_fraction::decimal_to_fraction; pub use self::doomsday::get_week_day; pub use self::elliptic_curve::EllipticCurve; pub use self::euclidean_distance::euclidean_distance; pub use self::exponential_linear_unit::exponential_linear_unit; pub use self::extended_euclidean_algorithm::extended_euclidean_algorithm; pub use self::factorial::{factorial, factorial_bigmath, factorial_recursive}; pub use self::factors::factors; pub use self::fast_fourier_transform::{ fast_fourier_transform, fast_fourier_transform_input_permutation, inverse_fast_fourier_transform, }; pub use self::fast_power::fast_power; pub use self::faster_perfect_numbers::generate_perfect_numbers; pub use self::field::{Field, PrimeField}; pub use self::frizzy_number::get_nth_frizzy; pub use self::gaussian_elimination::gaussian_elimination; pub use self::gaussian_error_linear_unit::gaussian_error_linear_unit; pub use self::gcd_of_n_numbers::gcd; pub use self::geometric_series::geometric_series; pub use self::greatest_common_divisor::{ greatest_common_divisor_iterative, greatest_common_divisor_recursive, greatest_common_divisor_stein, }; pub use self::huber_loss::huber_loss; pub use self::infix_to_postfix::infix_to_postfix; pub use self::interest::{compound_interest, simple_interest}; pub use self::interpolation::{lagrange_polynomial_interpolation, linear_interpolation}; pub use self::interquartile_range::interquartile_range; pub use self::karatsuba_multiplication::multiply; pub use self::lcm_of_n_numbers::lcm; pub use self::leaky_relu::leaky_relu; pub use self::least_square_approx::least_square_approx; pub use self::linear_sieve::LinearSieve; pub use self::logarithm::log; pub use self::lucas_series::dynamic_lucas_number; pub use self::lucas_series::recursive_lucas_number; pub use self::matrix_ops::Matrix; pub use self::mersenne_primes::{get_mersenne_primes, is_mersenne_prime}; pub use self::miller_rabin::{big_miller_rabin, miller_rabin}; pub use self::modular_exponential::{mod_inverse, modular_exponential}; pub use self::newton_raphson::find_root; pub use self::nthprime::nthprime; pub use self::pascal_triangle::pascal_triangle; pub use self::perfect_cube::perfect_cube_binary_search; pub use self::perfect_numbers::perfect_numbers; pub use self::perfect_square::perfect_square; pub use self::perfect_square::perfect_square_binary_search; pub use self::pollard_rho::{pollard_rho_factorize, pollard_rho_get_one_factor}; pub use self::postfix_evaluation::evaluate_postfix; pub use self::prime_check::prime_check; pub use self::prime_factors::prime_factors; pub use self::prime_numbers::prime_numbers; pub use self::quadratic_residue::{cipolla, tonelli_shanks}; pub use self::random::PCG32; pub use self::relu::relu; pub use self::sieve_of_eratosthenes::sieve_of_eratosthenes; pub use self::sigmoid::sigmoid; pub use self::signum::signum; pub use self::simpsons_integration::simpsons_integration; pub use self::softmax::softmax; pub use self::sprague_grundy_theorem::calculate_grundy_number; pub use self::square_pyramidal_numbers::square_pyramidal_number; pub use self::square_root::{fast_inv_sqrt, square_root}; pub use self::sum_of_digits::{sum_digits_iterative, sum_digits_recursive}; pub use self::sum_of_geometric_progression::sum_of_geometric_progression; pub use self::sum_of_harmonic_series::sum_of_harmonic_progression; 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::trig_functions::cosine; pub use self::trig_functions::cosine_no_radian_arg; pub use self::trig_functions::cotan; pub use self::trig_functions::cotan_no_radian_arg; pub use self::trig_functions::sine; pub use self::trig_functions::sine_no_radian_arg; pub use self::trig_functions::tan; pub use self::trig_functions::tan_no_radian_arg; pub use self::vector_cross_product::cross_product; pub use self::vector_cross_product::vector_magnitude; pub use self::zellers_congruence_algorithm::zellers_congruence_algorithm;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/trig_functions.rs
src/math/trig_functions.rs
/// Function that contains the similarities of the sine and cosine implementations /// /// Both of them are calculated using their MacLaurin Series /// /// Because there is just a '+1' that differs in their formula, this function has been /// created for not repeating fn template<T: Into<f64>>(x: T, tol: f64, kind: i32) -> f64 { use std::f64::consts::PI; const PERIOD: f64 = 2.0 * PI; /* Sometimes, this function is called for a big 'n'(when tol is very small) */ fn factorial(n: i128) -> i128 { (1..=n).product() } /* Function to round up to the 'decimal'th decimal of the number 'x' */ fn round_up_to_decimal(x: f64, decimal: i32) -> f64 { let multiplier = 10f64.powi(decimal); (x * multiplier).round() / multiplier } let mut value: f64 = x.into(); //<-- This is the line for which the trait 'Into' is required /* Check for invalid arguments */ if !value.is_finite() || value.is_nan() { eprintln!("This function does not accept invalid arguments."); return f64::NAN; } /* The argument to sine could be bigger than the sine's PERIOD To prevent overflowing, strip the value off relative to the PERIOD */ while value >= PERIOD { value -= PERIOD; } /* For cases when the value is smaller than the -PERIOD (e.g. sin(-3π) <=> sin(-π)) */ while value <= -PERIOD { value += PERIOD; } let mut rez = 0f64; let mut prev_rez = 1f64; let mut step: i32 = 0; /* This while instruction is the MacLaurin Series for sine / cosine sin(x) = Σ (-1)^n * x^2n+1 / (2n+1)!, for n >= 0 and x a Real number cos(x) = Σ (-1)^n * x^2n / (2n)!, for n >= 0 and x a Real number '+1' in sine's formula is replaced with 'kind', which values are: -> kind = 0, for cosine -> kind = 1, for sine */ while (prev_rez - rez).abs() > tol { prev_rez = rez; rez += (-1f64).powi(step) * value.powi(2 * step + kind) / factorial((2 * step + kind) as i128) as f64; step += 1; } /* Round up to the 6th decimal */ round_up_to_decimal(rez, 6) } /// Returns the value of sin(x), approximated with the given tolerance /// /// This function supposes the argument is in radians /// /// ### Example /// /// sin(1) == sin(1 rad) == sin(π/180) pub fn sine<T: Into<f64>>(x: T, tol: f64) -> f64 { template(x, tol, 1) } /// Returns the value of cos, approximated with the given tolerance, for /// an angle 'x' in radians pub fn cosine<T: Into<f64>>(x: T, tol: f64) -> f64 { template(x, tol, 0) } /// Cosine of 'x' in degrees, with the given tolerance pub fn cosine_no_radian_arg<T: Into<f64>>(x: T, tol: f64) -> f64 { use std::f64::consts::PI; let val: f64 = x.into(); cosine(val * PI / 180., tol) } /// Sine function for non radian angle /// /// Interprets the argument in degrees, not in radians /// /// ### Example /// /// sin(1<sup>o</sup>) != \[ sin(1 rad) == sin(π/180) \] pub fn sine_no_radian_arg<T: Into<f64>>(x: T, tol: f64) -> f64 { use std::f64::consts::PI; let val: f64 = x.into(); sine(val * PI / 180f64, tol) } /// Tangent of angle 'x' in radians, calculated with the given tolerance pub fn tan<T: Into<f64> + Copy>(x: T, tol: f64) -> f64 { let cos_val = cosine(x, tol); /* Cover special cases for division */ if cos_val == 0f64 { f64::NAN } else { let sin_val = sine(x, tol); sin_val / cos_val } } /// Cotangent of angle 'x' in radians, calculated with the given tolerance pub fn cotan<T: Into<f64> + Copy>(x: T, tol: f64) -> f64 { let sin_val = sine(x, tol); /* Cover special cases for division */ if sin_val == 0f64 { f64::NAN } else { let cos_val = cosine(x, tol); cos_val / sin_val } } /// Tangent of 'x' in degrees, approximated with the given tolerance pub fn tan_no_radian_arg<T: Into<f64> + Copy>(x: T, tol: f64) -> f64 { let angle: f64 = x.into(); use std::f64::consts::PI; tan(angle * PI / 180., tol) } /// Cotangent of 'x' in degrees, approximated with the given tolerance pub fn cotan_no_radian_arg<T: Into<f64> + Copy>(x: T, tol: f64) -> f64 { let angle: f64 = x.into(); use std::f64::consts::PI; cotan(angle * PI / 180., tol) } #[cfg(test)] mod tests { use super::*; use std::f64::consts::PI; enum TrigFuncType { Sine, Cosine, Tan, Cotan, } const TOL: f64 = 1e-10; impl TrigFuncType { fn verify<T: Into<f64> + Copy>(&self, angle: T, expected_result: f64, is_radian: bool) { let value = match self { TrigFuncType::Sine => { if is_radian { sine(angle, TOL) } else { sine_no_radian_arg(angle, TOL) } } TrigFuncType::Cosine => { if is_radian { cosine(angle, TOL) } else { cosine_no_radian_arg(angle, TOL) } } TrigFuncType::Tan => { if is_radian { tan(angle, TOL) } else { tan_no_radian_arg(angle, TOL) } } TrigFuncType::Cotan => { if is_radian { cotan(angle, TOL) } else { cotan_no_radian_arg(angle, TOL) } } }; assert_eq!(format!("{value:.5}"), format!("{:.5}", expected_result)); } } #[test] fn test_sine() { let sine_id = TrigFuncType::Sine; sine_id.verify(0.0, 0.0, true); sine_id.verify(-PI, 0.0, true); sine_id.verify(-PI / 2.0, -1.0, true); sine_id.verify(0.5, 0.4794255386, true); /* Same tests, but angle is now in degrees */ sine_id.verify(0, 0.0, false); sine_id.verify(-180, 0.0, false); sine_id.verify(-180 / 2, -1.0, false); sine_id.verify(0.5, 0.00872654, false); } #[test] fn test_sine_bad_arg() { assert!(sine(f64::NEG_INFINITY, 1e-1).is_nan()); assert!(sine_no_radian_arg(f64::NAN, 1e-1).is_nan()); } #[test] fn test_cosine_bad_arg() { assert!(cosine(f64::INFINITY, 1e-1).is_nan()); assert!(cosine_no_radian_arg(f64::NAN, 1e-1).is_nan()); } #[test] fn test_cosine() { let cosine_id = TrigFuncType::Cosine; cosine_id.verify(0, 1., true); cosine_id.verify(0, 1., false); cosine_id.verify(45, 1. / f64::sqrt(2.), false); cosine_id.verify(PI / 4., 1. / f64::sqrt(2.), true); cosine_id.verify(360, 1., false); cosine_id.verify(2. * PI, 1., true); cosine_id.verify(15. * PI / 2., 0.0, true); cosine_id.verify(-855, -1. / f64::sqrt(2.), false); } #[test] fn test_tan_bad_arg() { assert!(tan(PI / 2., TOL).is_nan()); assert!(tan(3. * PI / 2., TOL).is_nan()); } #[test] fn test_tan() { let tan_id = TrigFuncType::Tan; tan_id.verify(PI / 4., 1f64, true); tan_id.verify(45, 1f64, false); tan_id.verify(PI, 0f64, true); tan_id.verify(180 + 45, 1f64, false); tan_id.verify(60 - 2 * 180, 1.7320508075, false); tan_id.verify(30 + 180 - 180, 0.57735026919, false); } #[test] fn test_cotan_bad_arg() { assert!(cotan(tan(PI / 2., TOL), TOL).is_nan()); assert!(!cotan(0, TOL).is_finite()); } #[test] fn test_cotan() { let cotan_id = TrigFuncType::Cotan; cotan_id.verify(PI / 4., 1f64, true); cotan_id.verify(90 + 10 * 180, 0f64, false); cotan_id.verify(30 - 5 * 180, f64::sqrt(3.), false); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/binary_exponentiation.rs
src/math/binary_exponentiation.rs
// Binary exponentiation is an algorithm to compute a power in O(logN) where N is the power. // // For example, to naively compute n^100, we multiply n 99 times for a O(N) algorithm. // // With binary exponentiation we can reduce the number of muliplications by only finding the binary // exponents. n^100 = n^64 * n^32 * n^4. We can compute n^64 by ((((n^2)^2)^2)...), which is // logN multiplications. // // We know which binary exponents to add by looking at the set bits in the power. For 100, we know // the bits for 64, 32, and 4 are set. // Computes n^p pub fn binary_exponentiation(mut n: u64, mut p: u32) -> u64 { let mut result_pow: u64 = 1; while p > 0 { if p & 1 == 1 { result_pow *= n; } p >>= 1; n *= n; } result_pow } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { // Need to be careful about large exponents. It is easy to hit overflows. assert_eq!(binary_exponentiation(2, 3), 8); assert_eq!(binary_exponentiation(4, 12), 16777216); assert_eq!(binary_exponentiation(6, 12), 2176782336); assert_eq!(binary_exponentiation(10, 4), 10000); assert_eq!(binary_exponentiation(20, 3), 8000); assert_eq!(binary_exponentiation(3, 21), 10460353203); } #[test] fn up_to_ten() { // Compute all powers from up to ten, using the standard library as the source of truth. for i in 0..10 { for j in 0..10 { println!("{i}, {j}"); assert_eq!(binary_exponentiation(i, j), u64::pow(i, j)) } } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/sprague_grundy_theorem.rs
src/math/sprague_grundy_theorem.rs
/** * Sprague Grundy Theorem for combinatorial games like Nim * * The Sprague Grundy Theorem is a fundamental concept in combinatorial game theory, commonly used to analyze * games like Nim. It calculates the Grundy number (also known as the nimber) for a position in a game. * The Grundy number represents the game's position, and it helps determine the winning strategy. * * The Grundy number of a terminal state is 0; otherwise, it is recursively defined as the minimum * excludant (mex) of the Grundy values of possible next states. * * For more details on Sprague Grundy Theorem, you can visit:(https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem) * * Author : [Gyandeep](https://github.com/Gyan172004) */ pub fn calculate_grundy_number( position: i64, grundy_numbers: &mut [i64], possible_moves: &[i64], ) -> i64 { // Check if we've already calculated the Grundy number for this position. if grundy_numbers[position as usize] != -1 { return grundy_numbers[position as usize]; } // Base case: terminal state if position == 0 { grundy_numbers[0] = 0; return 0; } // Calculate Grundy values for possible next states. let mut next_state_grundy_values: Vec<i64> = vec![]; for move_size in possible_moves.iter() { if position - move_size >= 0 { next_state_grundy_values.push(calculate_grundy_number( position - move_size, grundy_numbers, possible_moves, )); } } // Sort the Grundy values and find the minimum excludant. next_state_grundy_values.sort_unstable(); let mut mex: i64 = 0; for grundy_value in next_state_grundy_values.iter() { if *grundy_value != mex { break; } mex += 1; } // Store the calculated Grundy number and return it. grundy_numbers[position as usize] = mex; mex } #[cfg(test)] mod tests { use super::*; #[test] fn calculate_grundy_number_test() { let mut grundy_numbers: Vec<i64> = vec![-1; 7]; let possible_moves: Vec<i64> = vec![1, 4]; calculate_grundy_number(6, &mut grundy_numbers, &possible_moves); assert_eq!(grundy_numbers, [0, 1, 0, 1, 2, 0, 1]); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/ceil.rs
src/math/ceil.rs
// In mathematics and computer science, the ceiling function maps x to the least integer greater than or equal to x // Source: https://en.wikipedia.org/wiki/Floor_and_ceiling_functions pub fn ceil(x: f64) -> f64 { let x_rounded_towards_zero = x as i32 as f64; if x < 0. || x_rounded_towards_zero == x { x_rounded_towards_zero } else { x_rounded_towards_zero + 1_f64 } } #[cfg(test)] mod tests { use super::*; #[test] fn positive_decimal() { let num = 1.10; assert_eq!(ceil(num), num.ceil()); } #[test] fn positive_decimal_with_small_number() { let num = 3.01; assert_eq!(ceil(num), num.ceil()); } #[test] fn positive_integer() { let num = 1.00; assert_eq!(ceil(num), num.ceil()); } #[test] fn negative_decimal() { let num = -1.10; assert_eq!(ceil(num), num.ceil()); } #[test] fn negative_decimal_with_small_number() { let num = -1.01; assert_eq!(ceil(num), num.ceil()); } #[test] fn negative_integer() { let num = -1.00; assert_eq!(ceil(num), num.ceil()); } #[test] fn zero() { let num = 0.00; assert_eq!(ceil(num), num.ceil()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/pollard_rho.rs
src/math/pollard_rho.rs
use super::miller_rabin; struct LinearCongruenceGenerator { // modulus as 2 ^ 32 multiplier: u32, increment: u32, state: u32, } impl LinearCongruenceGenerator { fn new(multiplier: u32, increment: u32, state: u32) -> Self { Self { multiplier, increment, state, } } fn next(&mut self) -> u32 { self.state = (self.multiplier as u64 * self.state as u64 + self.increment as u64) as u32; self.state } fn get_64bits(&mut self) -> u64 { ((self.next() as u64) << 32) | (self.next() as u64) } } fn gcd(mut a: u64, mut b: u64) -> u64 { while a != 0 { let tmp = b % a; b = a; a = tmp; } b } #[inline] fn advance(x: u128, c: u64, number: u64) -> u128 { ((x * x) + c as u128) % number as u128 } fn pollard_rho_customizable( number: u64, x0: u64, c: u64, iterations_before_check: u32, iterations_cutoff: u32, ) -> u64 { /* Here we are using Brent's method for finding cycle. It is generally faster because we will not use `advance` function as often as Floyd's method. We also wait to do a few iterations before calculating the GCD, because it is an expensive function. We will correct for overshooting later. This function may return either 1, `number` or a proper divisor of `number` */ let mut x = x0 as u128; // tortoise let mut x_start = 0_u128; // to save the starting tortoise if we overshoot let mut y = 0_u128; // hare let mut remainder = 1_u128; let mut current_gcd = 1_u64; let mut max_iterations = 1_u32; while current_gcd == 1 { y = x; for _ in 1..max_iterations { x = advance(x, c, number); } let mut big_iteration = 0_u32; while big_iteration < max_iterations && current_gcd == 1 { x_start = x; let mut small_iteration = 0_u32; while small_iteration < iterations_before_check && small_iteration < (max_iterations - big_iteration) { small_iteration += 1; x = advance(x, c, number); let diff = x.abs_diff(y); remainder = (remainder * diff) % number as u128; } current_gcd = gcd(remainder as u64, number); big_iteration += iterations_before_check; } max_iterations *= 2; if max_iterations > iterations_cutoff { break; } } if current_gcd == number { while current_gcd == 1 { x_start = advance(x_start, c, number); current_gcd = gcd(x_start.abs_diff(y) as u64, number); } } current_gcd } /* Note: using this function with `check_is_prime` = false and a prime number will result in an infinite loop. RNG's internal state is represented as `seed`. It is advisable (but not mandatory) to reuse the saved seed value In subsequent calls to this function. */ pub fn pollard_rho_get_one_factor(number: u64, seed: &mut u32, check_is_prime: bool) -> u64 { // LCG parameters from wikipedia let mut rng = LinearCongruenceGenerator::new(1103515245, 12345, *seed); if number <= 1 { return number; } if check_is_prime { let mut bases = vec![2u64, 3, 5, 7]; if number > 3_215_031_000 { bases.append(&mut vec![11, 13, 17, 19, 23, 29, 31, 37]); } if miller_rabin(number, &bases) == 0 { return number; } } let mut factor = 1u64; while factor == 1 || factor == number { let x = rng.get_64bits(); let c = rng.get_64bits(); factor = pollard_rho_customizable( number, (x % (number - 3)) + 2, (c % (number - 2)) + 1, 32, 1 << 18, // This shouldn't take much longer than number ^ 0.25 ); // These numbers were selected based on local testing. // For specific applications there maybe better choices. } *seed = rng.state; factor } fn get_small_factors(mut number: u64, primes: &[usize]) -> (u64, Vec<u64>) { let mut result: Vec<u64> = Vec::new(); for p in primes { while number.is_multiple_of(*p as u64) { number /= *p as u64; result.push(*p as u64); } } (number, result) } fn factor_using_mpf(mut number: usize, mpf: &[usize]) -> Vec<u64> { let mut result = Vec::new(); while number > 1 { result.push(mpf[number] as u64); number /= mpf[number]; } result } /* `primes` and `minimum_prime_factors` use usize because so does LinearSieve implementation in this repository */ pub fn pollard_rho_factorize( mut number: u64, seed: &mut u32, primes: &[usize], minimum_prime_factors: &[usize], ) -> Vec<u64> { if number <= 1 { return vec![]; } let mut result: Vec<u64> = Vec::new(); { // Create a new scope to keep the outer scope clean let (rem, mut res) = get_small_factors(number, primes); number = rem; result.append(&mut res); } if number == 1 { return result; } let mut to_be_factored = vec![number]; while let Some(last) = to_be_factored.pop() { if last < minimum_prime_factors.len() as u64 { result.append(&mut factor_using_mpf(last as usize, minimum_prime_factors)); continue; } let fact = pollard_rho_get_one_factor(last, seed, true); if fact == last { result.push(last); continue; } to_be_factored.push(fact); to_be_factored.push(last / fact); } result.sort_unstable(); result } #[cfg(test)] mod test { use super::super::LinearSieve; use super::*; fn check_is_proper_factor(number: u64, factor: u64) -> bool { factor > 1 && factor < number && number.is_multiple_of(factor) } fn check_factorization(number: u64, factors: &[u64]) -> bool { let bases = vec![2u64, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; let mut prod = 1_u64; let mut prime_check = 0_u64; for p in factors { prod *= *p; prime_check |= miller_rabin(*p, &bases); } prime_check == 0 && prod == number } #[test] fn one_factor() { // a few small cases let mut sieve = LinearSieve::new(); sieve.prepare(1e5 as usize).unwrap(); let numbers = vec![1235, 239874233, 4353234, 456456, 120983]; let mut seed = 314159_u32; // first digits of pi; nothing up my sleeve for num in numbers { let factor = pollard_rho_get_one_factor(num, &mut seed, true); assert!(check_is_proper_factor(num, factor)); let factor = pollard_rho_get_one_factor(num, &mut seed, false); assert!(check_is_proper_factor(num, factor)); assert!(check_factorization( num, &pollard_rho_factorize(num, &mut seed, &sieve.primes, &sieve.minimum_prime_factor) )); } // check if it goes into infinite loop if `number` is prime let numbers = vec![ 2, 3, 5, 7, 11, 13, 101, 998244353, 1000000007, 1000000009, 1671398671, 1652465729, 1894404511, 1683402997, 1661963047, 1946039987, 2071566551, 1867816303, 1952199377, 1622379469, 1739317499, 1775433631, 1994828917, 1818930719, 1672996277, ]; for num in numbers { assert_eq!(pollard_rho_get_one_factor(num, &mut seed, true), num); assert!(check_factorization( num, &pollard_rho_factorize(num, &mut seed, &sieve.primes, &sieve.minimum_prime_factor) )); } } #[test] fn big_numbers() { // Bigger cases: // Each of these numbers is a product of two 31 bit primes // This shouldn't take more than a 10ms per number on a modern PC let mut seed = 314159_u32; // first digits of pi; nothing up my sleeve let numbers: Vec<u64> = vec![ 2761929023323646159, 3189046231347719467, 3234246546378360389, 3869305776707280953, 3167208188639390813, 3088042782711408869, 3628455596280801323, 2953787574901819241, 3909561575378030219, 4357328471891213977, 2824368080144930999, 3348680054093203003, 2704267100962222513, 2916169237307181179, 3669851121098875703, ]; for num in numbers { assert!(check_factorization( num, &pollard_rho_factorize(num, &mut seed, &[], &[]) )); } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/mersenne_primes.rs
src/math/mersenne_primes.rs
// mersenne prime : https://en.wikipedia.org/wiki/Mersenne_prime pub fn is_mersenne_prime(n: usize) -> bool { if n == 2 { return true; } let mut s = 4; let m = 2_usize.pow(std::convert::TryInto::try_into(n).unwrap()) - 1; for _ in 0..n - 2 { s = ((s * s) - 2) % m; } s == 0 } pub fn get_mersenne_primes(limit: usize) -> Vec<usize> { let mut results: Vec<usize> = Vec::new(); for num in 1..=limit { if is_mersenne_prime(num) { results.push(num); } } results } #[cfg(test)] mod tests { use super::{get_mersenne_primes, is_mersenne_prime}; #[test] fn validity_check() { assert!(is_mersenne_prime(3)); assert!(is_mersenne_prime(13)); assert!(!is_mersenne_prime(32)); } #[allow(dead_code)] fn generation_check() { assert_eq!(get_mersenne_primes(30), [2, 3, 5, 7, 13, 17, 19]); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/simpsons_integration.rs
src/math/simpsons_integration.rs
pub fn simpsons_integration<F>(f: F, a: f64, b: f64, n: usize) -> f64 where F: Fn(f64) -> f64, { let h = (b - a) / n as f64; (0..n) .map(|i| { let x0 = a + i as f64 * h; let x1 = x0 + h / 2.0; let x2 = x0 + h; (h / 6.0) * (f(x0) + 4.0 * f(x1) + f(x2)) }) .sum() } #[cfg(test)] mod tests { use super::*; #[test] fn test_simpsons_integration() { let f = |x: f64| x.powi(2); let a = 0.0; let b = 1.0; let n = 100; let result = simpsons_integration(f, a, b, n); assert!((result - 1.0 / 3.0).abs() < 1e-6); } #[test] fn test_error() { let f = |x: f64| x.powi(2); let a = 0.0; let b = 1.0; let n = 100; let result = simpsons_integration(f, a, b, n); let error = (1.0 / 3.0 - result).abs(); assert!(error < 1e-6); } #[test] fn test_convergence() { let f = |x: f64| x.powi(2); let a = 0.0; let b = 1.0; let n = 100; let result1 = simpsons_integration(f, a, b, n); let result2 = simpsons_integration(f, a, b, 2 * n); let result3 = simpsons_integration(f, a, b, 4 * n); let result4 = simpsons_integration(f, a, b, 8 * n); assert!((result1 - result2).abs() < 1e-6); assert!((result2 - result3).abs() < 1e-6); assert!((result3 - result4).abs() < 1e-6); } #[test] fn test_negative() { let f = |x: f64| -x.powi(2); let a = 0.0; let b = 1.0; let n = 100; let result = simpsons_integration(f, a, b, n); assert!((result + 1.0 / 3.0).abs() < 1e-6); } #[test] fn test_non_zero_lower_bound() { let f = |x: f64| x.powi(2); let a = 1.0; let b = 2.0; let n = 100; let result = simpsons_integration(f, a, b, n); assert!((result - 7.0 / 3.0).abs() < 1e-6); } #[test] fn test_non_zero_upper_bound() { let f = |x: f64| x.powi(2); let a = 0.0; let b = 2.0; let n = 100; let result = simpsons_integration(f, a, b, n); assert!((result - 8.0 / 3.0).abs() < 1e-6); } #[test] fn test_non_zero_lower_and_upper_bound() { let f = |x: f64| x.powi(2); let a = 1.0; let b = 2.0; let n = 100; let result = simpsons_integration(f, a, b, n); assert!((result - 7.0 / 3.0).abs() < 1e-6); } #[test] fn test_non_zero_lower_and_upper_bound_negative() { let f = |x: f64| -x.powi(2); let a = 1.0; let b = 2.0; let n = 100; let result = simpsons_integration(f, a, b, n); assert!((result + 7.0 / 3.0).abs() < 1e-6); } #[test] fn parabola_curve_length() { // Calculate the length of the curve f(x) = x^2 for -5 <= x <= 5 // We should integrate sqrt(1 + (f'(x))^2) let function = |x: f64| -> f64 { (1.0 + 4.0 * x * x).sqrt() }; let result = simpsons_integration(function, -5.0, 5.0, 1_000); let integrated = |x: f64| -> f64 { (x * function(x) / 2.0) + ((2.0 * x).asinh() / 4.0) }; let expected = integrated(5.0) - integrated(-5.0); assert!((result - expected).abs() < 1e-9); } #[test] fn area_under_cosine() { use std::f64::consts::PI; // Calculate area under f(x) = cos(x) + 5 for -pi <= x <= pi // cosine should cancel out and the answer should be 2pi * 5 let function = |x: f64| -> f64 { x.cos() + 5.0 }; let result = simpsons_integration(function, -PI, PI, 1_000); let expected = 2.0 * PI * 5.0; assert!((result - expected).abs() < 1e-9); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/fast_fourier_transform.rs
src/math/fast_fourier_transform.rs
use std::ops::{Add, Mul, MulAssign, Sub}; // f64 complex #[derive(Clone, Copy, Debug)] pub struct Complex64 { pub re: f64, pub im: f64, } impl Complex64 { #[inline] pub fn new(re: f64, im: f64) -> Self { Self { re, im } } #[inline] pub fn square_norm(&self) -> f64 { self.re * self.re + self.im * self.im } #[inline] pub fn norm(&self) -> f64 { self.square_norm().sqrt() } #[inline] pub fn inverse(&self) -> Complex64 { let nrm = self.square_norm(); Complex64 { re: self.re / nrm, im: -self.im / nrm, } } } impl Default for Complex64 { #[inline] fn default() -> Self { Self { re: 0.0, im: 0.0 } } } impl Add<Complex64> for Complex64 { type Output = Complex64; #[inline] fn add(self, other: Complex64) -> Complex64 { Complex64 { re: self.re + other.re, im: self.im + other.im, } } } impl Sub<Complex64> for Complex64 { type Output = Complex64; #[inline] fn sub(self, other: Complex64) -> Complex64 { Complex64 { re: self.re - other.re, im: self.im - other.im, } } } impl Mul<Complex64> for Complex64 { type Output = Complex64; #[inline] fn mul(self, other: Complex64) -> Complex64 { Complex64 { re: self.re * other.re - self.im * other.im, im: self.re * other.im + self.im * other.re, } } } impl MulAssign<Complex64> for Complex64 { #[inline] fn mul_assign(&mut self, other: Complex64) { let tmp = self.re * other.im + self.im * other.re; self.re = self.re * other.re - self.im * other.im; self.im = tmp; } } pub fn fast_fourier_transform_input_permutation(length: usize) -> Vec<usize> { let mut result = Vec::new(); result.reserve_exact(length); for i in 0..length { result.push(i); } let mut reverse = 0_usize; let mut position = 1_usize; while position < length { let mut bit = length >> 1; while bit & reverse != 0 { reverse ^= bit; bit >>= 1; } reverse ^= bit; // This is equivalent to adding 1 to a reversed number if position < reverse { // Only swap each element once result.swap(position, reverse); } position += 1; } result } pub fn fast_fourier_transform(input: &[f64], input_permutation: &[usize]) -> Vec<Complex64> { let n = input.len(); let mut result = Vec::new(); result.reserve_exact(n); for position in input_permutation { result.push(Complex64::new(input[*position], 0.0)); } let mut segment_length = 1_usize; while segment_length < n { segment_length <<= 1; let angle: f64 = std::f64::consts::TAU / segment_length as f64; let w_len = Complex64::new(angle.cos(), angle.sin()); for segment_start in (0..n).step_by(segment_length) { let mut w = Complex64::new(1.0, 0.0); for position in segment_start..(segment_start + segment_length / 2) { let a = result[position]; let b = result[position + segment_length / 2] * w; result[position] = a + b; result[position + segment_length / 2] = a - b; w *= w_len; } } } result } pub fn inverse_fast_fourier_transform( input: &[Complex64], input_permutation: &[usize], ) -> Vec<f64> { let n = input.len(); let mut result = Vec::new(); result.reserve_exact(n); for position in input_permutation { result.push(input[*position]); } let mut segment_length = 1_usize; while segment_length < n { segment_length <<= 1; let angle: f64 = -std::f64::consts::TAU / segment_length as f64; let w_len = Complex64::new(angle.cos(), angle.sin()); for segment_start in (0..n).step_by(segment_length) { let mut w = Complex64::new(1.0, 0.0); for position in segment_start..(segment_start + segment_length / 2) { let a = result[position]; let b = result[position + segment_length / 2] * w; result[position] = a + b; result[position + segment_length / 2] = a - b; w *= w_len; } } } let scale = 1.0 / n as f64; result.iter().map(|x| x.re * scale).collect() } #[cfg(test)] mod tests { use super::*; fn almost_equal(a: f64, b: f64, epsilon: f64) -> bool { (a - b).abs() < epsilon } const EPSILON: f64 = 1e-6; #[test] fn small_polynomial_returns_self() { let polynomial = vec![1.0f64, 1.0, 0.0, 2.5]; let permutation = fast_fourier_transform_input_permutation(polynomial.len()); let fft = fast_fourier_transform(&polynomial, &permutation); let ifft = inverse_fast_fourier_transform(&fft, &permutation); for (x, y) in ifft.iter().zip(polynomial.iter()) { assert!(almost_equal(*x, *y, EPSILON)); } } #[test] fn square_small_polynomial() { let mut polynomial = vec![1.0f64, 1.0, 0.0, 2.0]; polynomial.append(&mut vec![0.0; 4]); let permutation = fast_fourier_transform_input_permutation(polynomial.len()); let mut fft = fast_fourier_transform(&polynomial, &permutation); for num in fft.iter_mut() { *num *= *num; } let ifft = inverse_fast_fourier_transform(&fft, &permutation); let expected = [1.0, 2.0, 1.0, 4.0, 4.0, 0.0, 4.0, 0.0, 0.0]; for (x, y) in ifft.iter().zip(expected.iter()) { assert!(almost_equal(*x, *y, EPSILON)); } } #[test] #[ignore] fn square_big_polynomial() { // This test case takes ~1050ms on my machine in unoptimized mode, // but it takes ~70ms in release mode. let n = 1 << 17; // ~100_000 let mut polynomial = vec![1.0f64; n]; polynomial.append(&mut vec![0.0f64; n]); let permutation = fast_fourier_transform_input_permutation(polynomial.len()); let mut fft = fast_fourier_transform(&polynomial, &permutation); for num in fft.iter_mut() { *num *= *num; } let ifft = inverse_fast_fourier_transform(&fft, &permutation); let expected = (0..((n << 1) - 1)).map(|i| std::cmp::min(i + 1, (n << 1) - 1 - i) as f64); for (&x, y) in ifft.iter().zip(expected) { assert!(almost_equal(x, y, EPSILON)); } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/sylvester_sequence.rs
src/math/sylvester_sequence.rs
// Author : cyrixninja // Sylvester Series : Calculates the nth number in Sylvester's sequence. // Wikipedia Reference : https://en.wikipedia.org/wiki/Sylvester%27s_sequence // Other References : https://the-algorithms.com/algorithm/sylvester-sequence?lang=python pub fn sylvester(number: i32) -> i128 { assert!(number > 0, "The input value of [n={number}] has to be > 0"); if number == 1 { 2 } else { let num = sylvester(number - 1); let lower = num - 1; let upper = num; lower * upper + 1 } } #[cfg(test)] mod tests { use super::*; #[test] fn test_sylvester() { assert_eq!(sylvester(8), 113423713055421844361000443_i128); } #[test] #[should_panic(expected = "The input value of [n=-1] has to be > 0")] fn test_sylvester_negative() { sylvester(-1); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/cross_entropy_loss.rs
src/math/cross_entropy_loss.rs
//! # Cross-Entropy Loss Function //! //! The `cross_entropy_loss` function calculates the cross-entropy loss between the actual and predicted probability distributions. //! //! Cross-entropy loss is commonly used in machine learning and deep learning to measure the dissimilarity between two probability distributions. It is often used in classification problems. //! //! ## Formula //! //! For a pair of actual and predicted probability distributions represented as vectors `actual` and `predicted`, the cross-entropy loss is calculated as: //! //! `L = -Σ(actual[i] * ln(predicted[i]))` for all `i` in the range of the vectors //! //! Where `ln` is the natural logarithm function, and `Σ` denotes the summation over all elements of the vectors. //! //! ## Cross-Entropy Loss Function Implementation //! //! This implementation takes two references to vectors of f64 values, `actual` and `predicted`, and returns the cross-entropy loss between them. //! pub fn cross_entropy_loss(actual: &[f64], predicted: &[f64]) -> f64 { let mut loss: Vec<f64> = Vec::new(); for (a, p) in actual.iter().zip(predicted.iter()) { loss.push(-a * p.ln()); } loss.iter().sum() } #[cfg(test)] mod tests { use super::*; #[test] fn test_cross_entropy_loss() { let test_vector_actual = vec![0., 1., 0., 0., 0., 0.]; let test_vector = vec![0.1, 0.7, 0.1, 0.05, 0.05, 0.1]; assert_eq!( cross_entropy_loss(&test_vector_actual, &test_vector), 0.35667494393873245 ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/vector_cross_product.rs
src/math/vector_cross_product.rs
/// Cross Product and Magnitude Calculation /// /// This program defines functions to calculate the cross product of two 3D vectors /// and the magnitude of a vector from its direction ratios. The main purpose is /// to demonstrate the mathematical concepts and provide test cases for the functions. /// /// Time Complexity: /// - Calculating the cross product and magnitude of a vector each takes O(1) time /// since we are working with fixed-size arrays and performing a fixed number of /// mathematical operations. /// Function to calculate the cross product of two vectors pub fn cross_product(vec1: [f64; 3], vec2: [f64; 3]) -> [f64; 3] { let x = vec1[1] * vec2[2] - vec1[2] * vec2[1]; let y = -(vec1[0] * vec2[2] - vec1[2] * vec2[0]); let z = vec1[0] * vec2[1] - vec1[1] * vec2[0]; [x, y, z] } /// Function to calculate the magnitude of a vector pub fn vector_magnitude(vec: [f64; 3]) -> f64 { (vec[0].powi(2) + vec[1].powi(2) + vec[2].powi(2)).sqrt() } #[cfg(test)] mod tests { use super::*; #[test] fn test_cross_product_and_magnitude_1() { // Test case with non-trivial vectors let vec1 = [1.0, 2.0, 3.0]; let vec2 = [4.0, 5.0, 6.0]; let cross_product = cross_product(vec1, vec2); let magnitude = vector_magnitude(cross_product); // Check the expected results with a tolerance for floating-point comparisons assert_eq!(cross_product, [-3.0, 6.0, -3.0]); assert!((magnitude - 7.34847).abs() < 1e-5); } #[test] fn test_cross_product_and_magnitude_2() { // Test case with orthogonal vectors let vec1 = [1.0, 0.0, 0.0]; let vec2 = [0.0, 1.0, 0.0]; let cross_product = cross_product(vec1, vec2); let magnitude = vector_magnitude(cross_product); // Check the expected results assert_eq!(cross_product, [0.0, 0.0, 1.0]); assert_eq!(magnitude, 1.0); } #[test] fn test_cross_product_and_magnitude_3() { // Test case with vectors along the axes let vec1 = [2.0, 0.0, 0.0]; let vec2 = [0.0, 3.0, 0.0]; let cross_product = cross_product(vec1, vec2); let magnitude = vector_magnitude(cross_product); // Check the expected results assert_eq!(cross_product, [0.0, 0.0, 6.0]); assert_eq!(magnitude, 6.0); } #[test] fn test_cross_product_and_magnitude_4() { // Test case with parallel vectors let vec1 = [1.0, 2.0, 3.0]; let vec2 = [2.0, 4.0, 6.0]; let cross_product = cross_product(vec1, vec2); let magnitude = vector_magnitude(cross_product); // Check the expected results assert_eq!(cross_product, [0.0, 0.0, 0.0]); assert_eq!(magnitude, 0.0); } #[test] fn test_cross_product_and_magnitude_5() { // Test case with zero vectors let vec1 = [0.0, 0.0, 0.0]; let vec2 = [0.0, 0.0, 0.0]; let cross_product = cross_product(vec1, vec2); let magnitude = vector_magnitude(cross_product); // Check the expected results assert_eq!(cross_product, [0.0, 0.0, 0.0]); assert_eq!(magnitude, 0.0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/prime_factors.rs
src/math/prime_factors.rs
// Finds the prime factors of a number in increasing order, with repetition. pub fn prime_factors(n: u64) -> Vec<u64> { let mut i = 2; let mut n = n; let mut factors = Vec::new(); while i * i <= n { if n.is_multiple_of(i) { n /= i; factors.push(i); } else { if i != 2 { i += 1; } i += 1; } } if n > 1 { factors.push(n); } factors } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(prime_factors(0), vec![]); assert_eq!(prime_factors(1), vec![]); assert_eq!(prime_factors(11), vec![11]); assert_eq!(prime_factors(25), vec![5, 5]); assert_eq!(prime_factors(33), vec![3, 11]); assert_eq!(prime_factors(2560), vec![2, 2, 2, 2, 2, 2, 2, 2, 2, 5]); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/interpolation.rs
src/math/interpolation.rs
/// In mathematics, linear interpolation is a method of curve fitting /// using linear polynomials to construct new data points within the range of a discrete set of known data points. /// Formula: y = y0 + (x - x0) * (y1 - y0) / (x1 - x0) /// Source: https://en.wikipedia.org/wiki/Linear_interpolation /// point0 and point1 are a tuple containing x and y values we want to interpolate between pub fn linear_interpolation(x: f64, point0: (f64, f64), point1: (f64, f64)) -> f64 { point0.1 + (x - point0.0) * (point1.1 - point0.1) / (point1.0 - point0.0) } /// In numerical analysis, the Lagrange interpolating polynomial /// is the unique polynomial of lowest degree that interpolates a given set of data. /// /// Source: https://en.wikipedia.org/wiki/Lagrange_polynomial /// Source: https://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html /// x is the point we wish to interpolate /// defined points are a vector of tuples containing known x and y values of our function pub fn lagrange_polynomial_interpolation(x: f64, defined_points: &Vec<(f64, f64)>) -> f64 { let mut defined_x_values: Vec<f64> = Vec::new(); let mut defined_y_values: Vec<f64> = Vec::new(); for (x, y) in defined_points { defined_x_values.push(*x); defined_y_values.push(*y); } let mut sum = 0.0; for y_index in 0..defined_y_values.len() { let mut numerator = 1.0; let mut denominator = 1.0; for x_index in 0..defined_x_values.len() { if y_index == x_index { continue; } denominator *= defined_x_values[y_index] - defined_x_values[x_index]; numerator *= x - defined_x_values[x_index]; } sum += numerator / denominator * defined_y_values[y_index]; } sum } #[cfg(test)] mod tests { use std::assert_eq; use super::*; #[test] fn test_linear_intepolation() { let point1 = (0.0, 0.0); let point2 = (1.0, 1.0); let point3 = (2.0, 2.0); let x1 = 0.5; let x2 = 1.5; let y1 = linear_interpolation(x1, point1, point2); let y2 = linear_interpolation(x2, point2, point3); assert_eq!(y1, x1); assert_eq!(y2, x2); assert_eq!( linear_interpolation(x1, point1, point2), linear_interpolation(x1, point2, point1) ); } #[test] fn test_lagrange_polynomial_interpolation() { // defined values for x^2 function let defined_points = vec![(0.0, 0.0), (1.0, 1.0), (2.0, 4.0), (3.0, 9.0)]; // check for equality assert_eq!(lagrange_polynomial_interpolation(1.0, &defined_points), 1.0); assert_eq!(lagrange_polynomial_interpolation(2.0, &defined_points), 4.0); assert_eq!(lagrange_polynomial_interpolation(3.0, &defined_points), 9.0); //other assert_eq!( lagrange_polynomial_interpolation(0.5, &defined_points), 0.25 ); assert_eq!( lagrange_polynomial_interpolation(2.5, &defined_points), 6.25 ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/lucas_series.rs
src/math/lucas_series.rs
// Author : cyrixninja // Lucas Series : Function to get the Nth Lucas Number // Wikipedia Reference : https://en.wikipedia.org/wiki/Lucas_number // Other References : https://the-algorithms.com/algorithm/lucas-series?lang=python pub fn recursive_lucas_number(n: u32) -> u32 { match n { 0 => 2, 1 => 1, _ => recursive_lucas_number(n - 1) + recursive_lucas_number(n - 2), } } pub fn dynamic_lucas_number(n: u32) -> u32 { let mut a = 2; let mut b = 1; for _ in 0..n { let temp = a; a = b; b += temp; } a } #[cfg(test)] mod tests { use super::*; macro_rules! test_lucas_number { ($($name:ident: $inputs:expr,)*) => { $( #[test] fn $name() { let (n, expected) = $inputs; assert_eq!(recursive_lucas_number(n), expected); assert_eq!(dynamic_lucas_number(n), expected); } )* } } test_lucas_number! { input_0: (0, 2), input_1: (1, 1), input_2: (2, 3), input_3: (3, 4), input_4: (4, 7), input_5: (5, 11), input_6: (6, 18), input_7: (7, 29), input_8: (8, 47), input_9: (9, 76), input_10: (10, 123), input_15: (15, 1364), input_20: (20, 15127), input_25: (25, 167761), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/aliquot_sum.rs
src/math/aliquot_sum.rs
/// Aliquot sum of a number is defined as the sum of the proper divisors of a number.\ /// i.e. all the divisors of a number apart from the number itself. /// /// ## Example: /// The aliquot sum of 6 is (1 + 2 + 3) = 6, and that of 15 is (1 + 3 + 5) = 9 /// /// Wikipedia article on Aliquot Sum: <https://en.wikipedia.org/wiki/Aliquot_sum> pub fn aliquot_sum(number: u64) -> u64 { if number == 0 { panic!("Input has to be positive.") } (1..=number / 2).filter(|&d| number.is_multiple_of(d)).sum() } #[cfg(test)] mod tests { use super::*; macro_rules! test_aliquot_sum { ($($name:ident: $tc:expr,)*) => { $( #[test] fn $name() { let (number, expected) = $tc; assert_eq!(aliquot_sum(number), expected); } )* } } test_aliquot_sum! { test_with_1: (1, 0), test_with_2: (2, 1), test_with_3: (3, 1), test_with_4: (4, 1+2), test_with_5: (5, 1), test_with_6: (6, 6), test_with_7: (7, 1), test_with_8: (8, 1+2+4), test_with_9: (9, 1+3), test_with_10: (10, 1+2+5), test_with_15: (15, 9), test_with_343: (343, 57), test_with_344: (344, 316), test_with_500: (500, 592), test_with_501: (501, 171), } #[test] #[should_panic] fn panics_if_input_is_zero() { aliquot_sum(0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/logarithm.rs
src/math/logarithm.rs
use std::f64::consts::E; /// Calculates the **log<sub>base</sub>(x)** /// /// Parameters: /// <p>-> base: base of log /// <p>-> x: value for which log shall be evaluated /// <p>-> tol: tolerance; the precision of the approximation (submultiples of 10<sup>-1</sup>) /// /// Advisable to use **std::f64::consts::*** for specific bases (like 'e') pub fn log<T: Into<f64>, U: Into<f64>>(base: U, x: T, tol: f64) -> f64 { let mut rez = 0f64; let mut argument: f64 = x.into(); let usable_base: f64 = base.into(); if argument <= 0f64 || usable_base <= 0f64 { println!("Log does not support negative argument or negative base."); f64::NAN } else if argument < 1f64 && usable_base == E { argument -= 1f64; let mut prev_rez = 1f64; let mut step: i32 = 1; /* For x in (0, 1) and base 'e', the function is using MacLaurin Series: ln(|1 + x|) = Σ "(-1)^n-1 * x^n / n", for n = 1..inf Substituting x with x-1 yields: ln(|x|) = Σ "(-1)^n-1 * (x-1)^n / n" */ while (prev_rez - rez).abs() > tol { prev_rez = rez; rez += (-1f64).powi(step - 1) * argument.powi(step) / step as f64; step += 1; } rez } else { /* Using the basic change of base formula for log */ let ln_x = argument.ln(); let ln_base = usable_base.ln(); ln_x / ln_base } } #[cfg(test)] mod test { use super::*; #[test] fn basic() { assert_eq!(log(E, E, 0.0), 1.0); assert_eq!(log(E, E.powi(100), 0.0), 100.0); assert_eq!(log(10, 10000.0, 0.0), 4.0); assert_eq!(log(234501.0, 1.0, 1.0), 0.0); } #[test] fn test_log_positive_base() { assert_eq!(log(10.0, 100.0, 0.00001), 2.0); assert_eq!(log(2.0, 8.0, 0.00001), 3.0); } #[test] fn test_log_zero_base() { assert!(log(0.0, 100.0, 0.00001).is_nan()); } #[test] fn test_log_negative_base() { assert!(log(-1.0, 100.0, 0.00001).is_nan()); } #[test] fn test_log_tolerance() { assert_eq!(log(10.0, 100.0, 1e-10), 2.0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/lcm_of_n_numbers.rs
src/math/lcm_of_n_numbers.rs
// returns the least common multiple of n numbers pub fn lcm(nums: &[usize]) -> usize { if nums.len() == 1 { return nums[0]; } let a = nums[0]; let b = lcm(&nums[1..]); a * b / gcd_of_two_numbers(a, b) } fn gcd_of_two_numbers(a: usize, b: usize) -> usize { if b == 0 { return a; } gcd_of_two_numbers(b, a % b) } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(lcm(&[1, 2, 3, 4, 5]), 60); assert_eq!(lcm(&[2, 4, 6, 8, 10]), 120); assert_eq!(lcm(&[3, 6, 9, 12, 15]), 180); assert_eq!(lcm(&[10]), 10); assert_eq!(lcm(&[21, 110]), 2310); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/least_square_approx.rs
src/math/least_square_approx.rs
/// Least Square Approximation <p> /// Function that returns a polynomial which very closely passes through the given points (in 2D) /// /// The result is made of coeficients, in descending order (from x^degree to free term) /// /// Parameters: /// /// points -> coordinates of given points /// /// degree -> degree of the polynomial /// pub fn least_square_approx<T: Into<f64> + Copy, U: Into<f64> + Copy>( points: &[(T, U)], degree: i32, ) -> Option<Vec<f64>> { use nalgebra::{DMatrix, DVector}; /* Used for rounding floating numbers */ fn round_to_decimals(value: f64, decimals: i32) -> f64 { let multiplier = 10f64.powi(decimals); (value * multiplier).round() / multiplier } /* Casting the data parsed to this function to f64 (as some points can have decimals) */ let vals: Vec<(f64, f64)> = points .iter() .map(|(x, y)| ((*x).into(), (*y).into())) .collect(); /* Because of collect we need the Copy Trait for T and U */ /* Computes the sums in the system of equations */ let mut sums = Vec::<f64>::new(); for i in 1..=(2 * degree + 1) { sums.push(vals.iter().map(|(x, _)| x.powi(i - 1)).sum()); } /* Compute the free terms column vector */ let mut free_col = Vec::<f64>::new(); for i in 1..=(degree + 1) { free_col.push(vals.iter().map(|(x, y)| y * (x.powi(i - 1))).sum()); } let b = DVector::from_row_slice(&free_col); /* Create and fill the system's matrix */ let size = (degree + 1) as usize; let a = DMatrix::from_fn(size, size, |i, j| sums[degree as usize + i - j]); /* Solve the system of equations: A * x = b */ match a.qr().solve(&b) { Some(x) => { let rez: Vec<f64> = x.iter().map(|x| round_to_decimals(*x, 5)).collect(); Some(rez) } None => None, //<-- The system cannot be solved (badly conditioned system's matrix) } } #[cfg(test)] mod tests { use super::*; #[test] fn ten_points_1st_degree() { let points = vec![ (5.3, 7.8), (4.9, 8.1), (6.1, 6.9), (4.7, 8.3), (6.5, 7.7), (5.6, 7.0), (5.8, 8.2), (4.5, 8.0), (6.3, 7.2), (5.1, 8.4), ]; assert_eq!( least_square_approx(&points, 1), Some(vec![-0.49069, 10.44898]) ); } #[test] fn eight_points_5th_degree() { let points = vec![ (4f64, 8f64), (8f64, 2f64), (1f64, 7f64), (10f64, 3f64), (11.0, 0.0), (7.0, 3.0), (10.0, 1.0), (13.0, 13.0), ]; assert_eq!( least_square_approx(&points, 5), Some(vec![ 0.00603, -0.21304, 2.79929, -16.53468, 40.29473, -19.35771 ]) ); } #[test] fn four_points_2nd_degree() { let points = vec![ (2.312, 8.345344), (-2.312, 8.345344), (-0.7051, 3.49716601), (0.7051, 3.49716601), ]; assert_eq!(least_square_approx(&points, 2), Some(vec![1.0, 0.0, 3.0])); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/miller_rabin.rs
src/math/miller_rabin.rs
use num_bigint::BigUint; use num_traits::{One, ToPrimitive, Zero}; use std::cmp::Ordering; fn modulo_power(mut base: u64, mut power: u64, modulo: u64) -> u64 { base %= modulo; if base == 0 { return 0; // return zero if base is divisible by modulo } let mut ans: u128 = 1; let mut bbase: u128 = base as u128; while power > 0 { if (power % 2) == 1 { ans = (ans * bbase) % (modulo as u128); } bbase = (bbase * bbase) % (modulo as u128); power /= 2; } ans as u64 } fn check_prime_base(number: u64, base: u64, two_power: u64, odd_power: u64) -> bool { // returns false if base is a witness let mut x: u128 = modulo_power(base, odd_power, number) as u128; let bnumber: u128 = number as u128; if x == 1 || x == (bnumber - 1) { return true; } for _ in 1..two_power { x = (x * x) % bnumber; if x == (bnumber - 1) { return true; } } false } pub fn miller_rabin(number: u64, bases: &[u64]) -> u64 { // returns zero on a probable prime, and a witness if number is not prime // A base set for deterministic performance on 64 bit numbers is: // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] // another one for 32 bits: // [2, 3, 5, 7], with smallest number to fail 3'215'031'751 = 151 * 751 * 28351 // note that all bases should be prime if number <= 4 { match number { 0 => { panic!("0 is invalid input for Miller-Rabin. 0 is not prime by definition, but has no witness"); } 2 | 3 => return 0, _ => return number, } } if bases.contains(&number) { return 0; } let two_power: u64 = (number - 1).trailing_zeros() as u64; let odd_power = (number - 1) >> two_power; for base in bases { if !check_prime_base(number, *base, two_power, odd_power) { return *base; } } 0 } pub fn big_miller_rabin(number_ref: &BigUint, bases: &[u64]) -> u64 { let number = number_ref.clone(); if BigUint::from(5u32).cmp(&number) == Ordering::Greater { if number.eq(&BigUint::zero()) { panic!("0 is invalid input for Miller-Rabin. 0 is not prime by definition, but has no witness"); } else if number.eq(&BigUint::from(2u32)) || number.eq(&BigUint::from(3u32)) { return 0; } else { return number.to_u64().unwrap(); } } if let Some(num) = number.to_u64() { if bases.contains(&num) { return 0; } } let num_minus_one = &number - BigUint::one(); let two_power: u64 = num_minus_one.trailing_zeros().unwrap(); let odd_power: BigUint = &num_minus_one >> two_power; for base in bases { let mut x = BigUint::from(*base).modpow(&odd_power, &number); if x.eq(&BigUint::one()) || x.eq(&num_minus_one) { continue; } let mut not_a_witness = false; for _ in 1..two_power { x = (&x * &x) % &number; if x.eq(&num_minus_one) { not_a_witness = true; break; } } if not_a_witness { continue; } return *base; } 0 } #[cfg(test)] mod tests { use super::*; static DEFAULT_BASES: [u64; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; #[test] fn basic() { // these bases make miller rabin deterministic for any number < 2 ^ 64 // can use smaller number of bases for deterministic performance for numbers < 2 ^ 32 assert_eq!(miller_rabin(3, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(7, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(11, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(2003, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(1, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(4, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(6, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(21, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(2004, &DEFAULT_BASES), 0); // bigger test cases. // primes are generated using openssl // non primes are randomly picked and checked using openssl // primes: assert_eq!(miller_rabin(3629611793, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(871594686869, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(968236663804121, &DEFAULT_BASES), 0); assert_eq!(miller_rabin(6920153791723773023, &DEFAULT_BASES), 0); // random non primes: assert_ne!(miller_rabin(4546167556336341257, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(4363186415423517377, &DEFAULT_BASES), 0); assert_ne!(miller_rabin(815479701131020226, &DEFAULT_BASES), 0); // these two are made of two 31 bit prime factors: // 1950202127 * 2058609037 = 4014703722618821699 assert_ne!(miller_rabin(4014703722618821699, &DEFAULT_BASES), 0); // 1679076769 * 2076341633 = 3486337000477823777 assert_ne!(miller_rabin(3486337000477823777, &DEFAULT_BASES), 0); } #[test] fn big_basic() { assert_eq!(big_miller_rabin(&BigUint::from(3u32), &DEFAULT_BASES), 0); assert_eq!(big_miller_rabin(&BigUint::from(7u32), &DEFAULT_BASES), 0); assert_eq!(big_miller_rabin(&BigUint::from(11u32), &DEFAULT_BASES), 0); assert_eq!(big_miller_rabin(&BigUint::from(2003u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(1u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(4u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(6u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(21u32), &DEFAULT_BASES), 0); assert_ne!(big_miller_rabin(&BigUint::from(2004u32), &DEFAULT_BASES), 0); assert_eq!( big_miller_rabin(&BigUint::from(3629611793u64), &DEFAULT_BASES), 0 ); assert_eq!( big_miller_rabin(&BigUint::from(871594686869u64), &DEFAULT_BASES), 0 ); assert_eq!( big_miller_rabin(&BigUint::from(968236663804121u64), &DEFAULT_BASES), 0 ); assert_eq!( big_miller_rabin(&BigUint::from(6920153791723773023u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(4546167556336341257u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(4363186415423517377u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(815479701131020226u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(4014703722618821699u64), &DEFAULT_BASES), 0 ); assert_ne!( big_miller_rabin(&BigUint::from(3486337000477823777u64), &DEFAULT_BASES), 0 ); } #[test] #[ignore] fn big_primes() { let p1 = BigUint::parse_bytes(b"4764862697132131451620315518348229845593592794669", 10).unwrap(); assert_eq!(big_miller_rabin(&p1, &DEFAULT_BASES), 0); let p2 = BigUint::parse_bytes( b"12550757946601963214089118080443488976766669415957018428703", 10, ) .unwrap(); assert_eq!(big_miller_rabin(&p2, &DEFAULT_BASES), 0); // An RSA-worthy prime let p3 = BigUint::parse_bytes(b"157d6l5zkv45ve4azfw7nyyjt6rzir2gcjoytjev5iacnkaii8hlkyk3op7bx9qfqiie23vj9iw4qbp7zupydfq9ut6mq6m36etya6cshtqi1yi9q5xyiws92el79dqt8qk7l2pqmxaa0sxhmd2vpaibo9dkfd029j1rvkwlw4724ctgaqs5jzy0bqi5pqdjc2xerhn", 36).unwrap(); assert_eq!(big_miller_rabin(&p3, &DEFAULT_BASES), 0); let n1 = BigUint::parse_bytes(b"coy6tkiaqswmce1r03ycdif3t796wzjwneewbe3cmncaplm85jxzcpdmvy0moic3lql70a81t5qdn2apac0dndhohewkspuk1wyndxsgxs3ux4a7730unru7dfmygh", 36).unwrap(); assert_ne!(big_miller_rabin(&n1, &DEFAULT_BASES), 0); // RSA-2048 let n2 = BigUint::parse_bytes(b"4l91lq4a2sgekpv8ukx1gxsk7mfeks46haggorlkazm0oufxwijid6q6v44u5me3kz3ne6yczp4fcvo62oej72oe7pjjtyxgid5b8xdz1e8daafspbzcy1hd8i4urjh9hm0tyylsgqsss3jn372d6fmykpw4bb9cr1ngxnncsbod3kg49o7owzqnsci5pwqt8bch0t60gq0st2gyx7ii3mzhb1pp1yvjyor35hwvok1sxj3ih46rpd27li8y5yli3mgdttcn65k3szfa6rbcnbgkojqjjq72gar6raslnh6sjd2fy7yj3bwo43obvbg3ws8y28kpol3okb5b3fld03sq1kgrj2fugiaxgplva6x5ssilqq4g0b21xy2kiou3sqsgonmqx55v", 36).unwrap(); assert_ne!(big_miller_rabin(&n2, &DEFAULT_BASES), 0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/frizzy_number.rs
src/math/frizzy_number.rs
/// This Rust program calculates the n-th Frizzy number for a given base. /// A Frizzy number is defined as the n-th number that is a sum of powers /// of the given base, with the powers corresponding to the binary representation /// of n. /// The `get_nth_frizzy` function takes two arguments: /// * `base` - The base whose n-th sum of powers is required. /// * `n` - Index from ascending order of the sum of powers of the base. /// It returns the n-th sum of powers of the base. /// # Example /// To find the Frizzy number with a base of 3 and n equal to 4: /// - Ascending order of sums of powers of 3: 3^0 = 1, 3^1 = 3, 3^1 + 3^0 = 4, 3^2 + 3^0 = 9. /// - The answer is 9. /// /// # Arguments /// * `base` - The base whose n-th sum of powers is required. /// * `n` - Index from ascending order of the sum of powers of the base. /// /// # Returns /// The n-th sum of powers of the base. pub fn get_nth_frizzy(base: i32, mut n: i32) -> f64 { let mut final1 = 0.0; let mut i = 0; while n > 0 { final1 += (base.pow(i) as f64) * ((n % 2) as f64); i += 1; n /= 2; } final1 } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_nth_frizzy() { // Test case 1: base = 3, n = 4 // 3^2 + 3^0 = 9 assert_eq!(get_nth_frizzy(3, 4), 9.0); // Test case 2: base = 2, n = 5 // 2^2 + 2^0 = 5 assert_eq!(get_nth_frizzy(2, 5), 5.0); // Test case 3: base = 4, n = 3 // 4^1 + 4^0 = 5 assert_eq!(get_nth_frizzy(4, 3), 5.0); // Test case 4: base = 5, n = 2 // 5^1 + 5^0 = 5 assert_eq!(get_nth_frizzy(5, 2), 5.0); // Test case 5: base = 6, n = 1 // 6^0 = 1 assert_eq!(get_nth_frizzy(6, 1), 1.0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/factorial.rs
src/math/factorial.rs
use num_bigint::BigUint; use num_traits::One; #[allow(unused_imports)] use std::str::FromStr; pub fn factorial(number: u64) -> u64 { // Base cases: 0! and 1! are both equal to 1 if number == 0 || number == 1 { 1 } else { // Calculate factorial using the product of the range from 2 to the given number (inclusive) (2..=number).product() } } pub fn factorial_recursive(n: u64) -> u64 { // Base cases: 0! and 1! are both equal to 1 if n == 0 || n == 1 { 1 } else { // Calculate factorial recursively by multiplying the current number with factorial of (n - 1) n * factorial_recursive(n - 1) } } pub fn factorial_bigmath(num: u32) -> BigUint { let mut result: BigUint = One::one(); for i in 1..=num { result *= i; } result } // Module for tests #[cfg(test)] mod tests { use super::*; // Test cases for the iterative factorial function #[test] fn test_factorial() { assert_eq!(factorial(0), 1); assert_eq!(factorial(1), 1); assert_eq!(factorial(6), 720); assert_eq!(factorial(10), 3628800); assert_eq!(factorial(20), 2432902008176640000); } // Test cases for the recursive factorial function #[test] fn test_factorial_recursive() { assert_eq!(factorial_recursive(0), 1); assert_eq!(factorial_recursive(1), 1); assert_eq!(factorial_recursive(6), 720); assert_eq!(factorial_recursive(10), 3628800); assert_eq!(factorial_recursive(20), 2432902008176640000); } #[test] fn basic_factorial() { assert_eq!(factorial_bigmath(10), BigUint::from_str("3628800").unwrap()); assert_eq!( factorial_bigmath(50), BigUint::from_str("30414093201713378043612608166064768844377641568960512000000000000") .unwrap() ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/sigmoid.rs
src/math/sigmoid.rs
//Rust implementation of the Sigmoid activation function. //The formula for Sigmoid: 1 / (1 + e^(-x)) //More information on the concepts of Sigmoid can be found here: //https://en.wikipedia.org/wiki/Sigmoid_function //The function below takes a reference to a mutable <f32> Vector as an argument //and returns the vector with 'Sigmoid' applied to all values. //Of course, these functions can be changed by the developer so that the input vector isn't manipulated. //This is simply an implemenation of the formula. use std::f32::consts::E; pub fn sigmoid(array: &mut Vec<f32>) -> &mut Vec<f32> { //note that these calculations are assuming the Vector values consists of real numbers in radians for value in &mut *array { *value = 1. / (1. + E.powf(-1. * *value)); } array } #[cfg(test)] mod tests { use super::*; #[test] fn test_sigmoid() { let mut test = Vec::from([1.0, 0.5, -1.0, 0.0, 0.3]); assert_eq!( sigmoid(&mut test), &mut Vec::<f32>::from([0.7310586, 0.62245935, 0.26894143, 0.5, 0.5744425,]) ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/chinese_remainder_theorem.rs
src/math/chinese_remainder_theorem.rs
use super::extended_euclidean_algorithm; fn mod_inv(x: i32, n: i32) -> Option<i32> { let (g, x, _) = extended_euclidean_algorithm(x, n); if g == 1 { Some((x % n + n) % n) } else { None } } pub fn chinese_remainder_theorem(residues: &[i32], modulli: &[i32]) -> Option<i32> { let prod = modulli.iter().product::<i32>(); let mut sum = 0; for (&residue, &modulus) in residues.iter().zip(modulli) { let p = prod / modulus; sum += residue * mod_inv(p, modulus)? * p } Some(sum % prod) } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(chinese_remainder_theorem(&[3, 5, 7], &[2, 3, 1]), Some(5)); assert_eq!(chinese_remainder_theorem(&[1, 4, 6], &[3, 5, 7]), Some(34)); assert_eq!(chinese_remainder_theorem(&[1, 4, 6], &[1, 2, 0]), None); assert_eq!(chinese_remainder_theorem(&[2, 5, 7], &[6, 9, 15]), None); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/geometric_series.rs
src/math/geometric_series.rs
// Author : cyrixninja // Wikipedia : https://en.wikipedia.org/wiki/Geometric_series // Calculate a geometric series. pub fn geometric_series(nth_term: f64, start_term_a: f64, common_ratio_r: f64) -> Vec<f64> { let mut series = Vec::new(); let mut multiple = 1.0; for _ in 0..(nth_term as i32) { series.push(start_term_a * multiple); multiple *= common_ratio_r; } series } #[cfg(test)] mod tests { use super::*; fn assert_approx_eq(a: f64, b: f64) { let epsilon = 1e-10; assert!((a - b).abs() < epsilon, "Expected {a}, found {b}"); } #[test] fn test_geometric_series() { let result = geometric_series(4.0, 2.0, 2.0); assert_eq!(result.len(), 4); assert_approx_eq(result[0], 2.0); assert_approx_eq(result[1], 4.0); assert_approx_eq(result[2], 8.0); assert_approx_eq(result[3], 16.0); let result = geometric_series(4.1, 2.1, 2.1); assert_eq!(result.len(), 4); assert_approx_eq(result[0], 2.1); assert_approx_eq(result[1], 4.41); assert_approx_eq(result[2], 9.261); assert_approx_eq(result[3], 19.4481); let result = geometric_series(4.0, -2.0, 2.0); assert_eq!(result.len(), 4); assert_approx_eq(result[0], -2.0); assert_approx_eq(result[1], -4.0); assert_approx_eq(result[2], -8.0); assert_approx_eq(result[3], -16.0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/combinations.rs
src/math/combinations.rs
// Function to calculate combinations of k elements from a set of n elements pub fn combinations(n: i64, k: i64) -> i64 { // Check if either n or k is negative, and panic if so if n < 0 || k < 0 { panic!("Please insert positive values"); } let mut res: i64 = 1; for i in 0..k { // Calculate the product of (n - i) and update the result res *= n - i; // Divide by (i + 1) to calculate the combination res /= i + 1; } res } #[cfg(test)] mod tests { use super::*; // Test case for combinations(10, 5) #[test] fn test_combinations_10_choose_5() { assert_eq!(combinations(10, 5), 252); } // Test case for combinations(6, 3) #[test] fn test_combinations_6_choose_3() { assert_eq!(combinations(6, 3), 20); } // Test case for combinations(20, 5) #[test] fn test_combinations_20_choose_5() { assert_eq!(combinations(20, 5), 15504); } // Test case for invalid input (negative values) #[test] #[should_panic(expected = "Please insert positive values")] fn test_combinations_invalid_input() { combinations(-5, 10); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/gcd_of_n_numbers.rs
src/math/gcd_of_n_numbers.rs
/// returns the greatest common divisor of n numbers pub fn gcd(nums: &[usize]) -> usize { if nums.len() == 1 { return nums[0]; } let a = nums[0]; let b = gcd(&nums[1..]); gcd_of_two_numbers(a, b) } fn gcd_of_two_numbers(a: usize, b: usize) -> usize { if b == 0 { return a; } gcd_of_two_numbers(b, a % b) } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(gcd(&[1, 2, 3, 4, 5]), 1); assert_eq!(gcd(&[2, 4, 6, 8, 10]), 2); assert_eq!(gcd(&[3, 6, 9, 12, 15]), 3); assert_eq!(gcd(&[10]), 10); assert_eq!(gcd(&[21, 110]), 1); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/math/nthprime.rs
src/math/nthprime.rs
// Generate the nth prime number. // Algorithm is inspired by the optimized version of the Sieve of Eratosthenes. pub fn nthprime(nth: u64) -> u64 { let mut total_prime: u64 = 0; let mut size_factor: u64 = 2; let mut s: u64 = nth * size_factor; let mut primes: Vec<u64> = Vec::new(); let n: u64 = nth; while total_prime < n { primes = get_primes(s).to_vec(); total_prime = primes[2..].iter().sum(); size_factor += 1; s = n * size_factor; } count_prime(primes, n).unwrap() } fn get_primes(s: u64) -> Vec<u64> { let mut v: Vec<u64> = vec![1; s as usize]; for index in 2..s { if v[index as usize] == 1 { for j in index..s { if index * j < s { v[(index * j) as usize] = 0; } else { break; } } } } v } fn count_prime(primes: Vec<u64>, n: u64) -> Option<u64> { let mut counter: u64 = 0; for (i, prime) in primes.iter().enumerate().skip(2) { counter += prime; if counter == n { return Some(i as u64); } } None } #[cfg(test)] mod tests { use super::*; #[test] fn my_test() { assert_eq!(nthprime(100), 541u64); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/polygon_points.rs
src/geometry/polygon_points.rs
type Ll = i64; type Pll = (Ll, Ll); fn cross(x1: Ll, y1: Ll, x2: Ll, y2: Ll) -> Ll { x1 * y2 - x2 * y1 } pub fn polygon_area(pts: &[Pll]) -> Ll { let mut ats = 0; for i in 2..pts.len() { ats += cross( pts[i].0 - pts[0].0, pts[i].1 - pts[0].1, pts[i - 1].0 - pts[0].0, pts[i - 1].1 - pts[0].1, ); } Ll::abs(ats / 2) } fn gcd(mut a: Ll, mut b: Ll) -> Ll { while b != 0 { let temp = b; b = a % b; a = temp; } a } fn boundary(pts: &[Pll]) -> Ll { let mut ats = pts.len() as Ll; for i in 0..pts.len() { let deltax = pts[i].0 - pts[(i + 1) % pts.len()].0; let deltay = pts[i].1 - pts[(i + 1) % pts.len()].1; ats += Ll::abs(gcd(deltax, deltay)) - 1; } ats } pub fn lattice_points(pts: &[Pll]) -> Ll { let bounds = boundary(pts); let area = polygon_area(pts); area + 1 - bounds / 2 } #[cfg(test)] mod tests { use super::*; #[test] fn test_calculate_cross() { assert_eq!(cross(1, 2, 3, 4), 4 - 3 * 2); } #[test] fn test_polygon_3_coordinates() { let pts = vec![(0, 0), (0, 3), (4, 0)]; assert_eq!(polygon_area(&pts), 6); } #[test] fn test_polygon_4_coordinates() { let pts = vec![(0, 0), (0, 2), (2, 2), (2, 0)]; assert_eq!(polygon_area(&pts), 4); } #[test] fn test_gcd_multiple_of_common_factor() { assert_eq!(gcd(14, 28), 14); } #[test] fn test_boundary() { let pts = vec![(0, 0), (0, 3), (0, 4), (2, 2)]; assert_eq!(boundary(&pts), 8); } #[test] fn test_lattice_points() { let pts = vec![(1, 1), (5, 1), (5, 4)]; let result = lattice_points(&pts); assert_eq!(result, 3); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/closest_points.rs
src/geometry/closest_points.rs
use crate::geometry::Point; use std::cmp::Ordering; fn cmp_x(p1: &Point, p2: &Point) -> Ordering { let acmp = f64_cmp(&p1.x, &p2.x); match acmp { Ordering::Equal => f64_cmp(&p1.y, &p2.y), _ => acmp, } } fn f64_cmp(a: &f64, b: &f64) -> Ordering { a.partial_cmp(b).unwrap() } /// returns the two closest points /// or None if there are zero or one point pub fn closest_points(points: &[Point]) -> Option<(Point, Point)> { let mut points_x: Vec<Point> = points.to_vec(); points_x.sort_by(cmp_x); let mut points_y = points_x.clone(); points_y.sort_by(|p1: &Point, p2: &Point| -> Ordering { p1.y.partial_cmp(&p2.y).unwrap() }); closest_points_aux(&points_x, points_y, 0, points_x.len()) } // We maintain two vectors with the same points, one sort by x coordinates and one sorted by y // coordinates. fn closest_points_aux( points_x: &[Point], points_y: Vec<Point>, mut start: usize, mut end: usize, ) -> Option<(Point, Point)> { let n = end - start; if n <= 1 { return None; } if n <= 3 { // bruteforce let mut min = points_x[0].euclidean_distance(&points_x[1]); let mut pair = (points_x[0].clone(), points_x[1].clone()); for i in 1..n { for j in (i + 1)..n { let new = points_x[i].euclidean_distance(&points_x[j]); if new < min { min = new; pair = (points_x[i].clone(), points_x[j].clone()); } } } return Some(pair); } let mid = start + (end - start) / 2; let mid_x = points_x[mid].x; // Separate points into y_left and y_right vectors based on their x-coordinate. Since y is // already sorted by y_axis, y_left and y_right will also be sorted. let mut y_left = vec![]; let mut y_right = vec![]; for point in &points_y { if point.x < mid_x { y_left.push(point.clone()); } else { y_right.push(point.clone()); } } let left = closest_points_aux(points_x, y_left, start, mid); let right = closest_points_aux(points_x, y_right, mid, end); let (mut min_sqr_dist, mut pair) = match (left, right) { (Some((l1, l2)), Some((r1, r2))) => { let dl = l1.euclidean_distance(&l2); let dr = r1.euclidean_distance(&r2); if dl < dr { (dl, (l1, l2)) } else { (dr, (r1, r2)) } } (Some((a, b)), None) | (None, Some((a, b))) => (a.euclidean_distance(&b), (a, b)), (None, None) => unreachable!(), }; let dist = min_sqr_dist; while points_x[start].x < mid_x - dist { start += 1; } while points_x[end - 1].x > mid_x + dist { end -= 1; } for (i, e) in points_y.iter().enumerate() { for k in 1..8 { if i + k >= points_y.len() { break; } let new = e.euclidean_distance(&points_y[i + k]); if new < min_sqr_dist { min_sqr_dist = new; pair = ((*e).clone(), points_y[i + k].clone()); } } } Some(pair) } #[cfg(test)] mod tests { use super::closest_points; use super::Point; fn eq(p1: Option<(Point, Point)>, p2: Option<(Point, Point)>) -> bool { match (p1, p2) { (None, None) => true, (Some((p1, p2)), Some((p3, p4))) => (p1 == p3 && p2 == p4) || (p1 == p4 && p2 == p3), _ => false, } } macro_rules! assert_display { ($left: expr, $right: expr) => { assert!( eq($left, $right), "assertion failed: `(left == right)`\nleft: `{:?}`,\nright: `{:?}`", $left, $right ) }; } #[test] fn zero_points() { let vals: [Point; 0] = []; assert_display!(closest_points(&vals), None::<(Point, Point)>); } #[test] fn one_points() { let vals = [Point::new(0., 0.)]; assert_display!(closest_points(&vals), None::<(Point, Point)>); } #[test] fn two_points() { let vals = [Point::new(0., 0.), Point::new(1., 1.)]; assert_display!( closest_points(&vals), Some((vals[0].clone(), vals[1].clone())) ); } #[test] fn three_points() { let vals = [Point::new(0., 0.), Point::new(1., 1.), Point::new(3., 3.)]; assert_display!( closest_points(&vals), Some((vals[0].clone(), vals[1].clone())) ); } #[test] fn list_1() { let vals = [ Point::new(0., 0.), Point::new(2., 1.), Point::new(5., 2.), Point::new(2., 3.), Point::new(4., 0.), Point::new(0., 4.), Point::new(5., 6.), Point::new(4., 4.), Point::new(7., 3.), Point::new(-1., 2.), Point::new(2., 6.), ]; assert_display!( closest_points(&vals), Some((Point::new(2., 1.), Point::new(2., 3.))) ); } #[test] fn list_2() { let vals = [ Point::new(1., 3.), Point::new(4., 6.), Point::new(8., 8.), Point::new(7., 5.), Point::new(5., 3.), Point::new(10., 3.), Point::new(7., 1.), Point::new(8., 3.), Point::new(4., 9.), Point::new(4., 12.), Point::new(4., 15.), Point::new(7., 14.), Point::new(8., 12.), Point::new(6., 10.), Point::new(4., 14.), Point::new(2., 7.), Point::new(3., 8.), Point::new(5., 8.), Point::new(6., 7.), Point::new(8., 10.), Point::new(6., 12.), ]; assert_display!( closest_points(&vals), Some((Point::new(4., 14.), Point::new(4., 15.))) ); } #[test] fn vertical_points() { let vals = [ Point::new(0., 0.), Point::new(0., 50.), Point::new(0., -25.), Point::new(0., 40.), Point::new(0., 42.), Point::new(0., 100.), Point::new(0., 17.), Point::new(0., 29.), Point::new(0., -50.), Point::new(0., 37.), Point::new(0., 34.), Point::new(0., 8.), Point::new(0., 3.), Point::new(0., 46.), ]; assert_display!( closest_points(&vals), Some((Point::new(0., 40.), Point::new(0., 42.))) ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/mod.rs
src/geometry/mod.rs
mod closest_points; mod graham_scan; mod jarvis_scan; mod point; mod polygon_points; mod ramer_douglas_peucker; mod segment; pub use self::closest_points::closest_points; pub use self::graham_scan::graham_scan; pub use self::jarvis_scan::jarvis_march; pub use self::point::Point; pub use self::polygon_points::lattice_points; pub use self::ramer_douglas_peucker::ramer_douglas_peucker; pub use self::segment::Segment;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/jarvis_scan.rs
src/geometry/jarvis_scan.rs
use crate::geometry::Point; use crate::geometry::Segment; // Returns a Vec of Points that make up the convex hull of `points`. Returns an empty Vec if there // is no convex hull. pub fn jarvis_march(points: Vec<Point>) -> Vec<Point> { if points.len() <= 2 { return vec![]; } let mut convex_hull = vec![]; let mut left_point = 0; for i in 1..points.len() { // Find the initial point, which is the leftmost point. In the case of a tie, we take the // bottom-most point. This helps prevent adding colinear points on the last segment to the hull. if points[i].x < points[left_point].x || (points[i].x == points[left_point].x && points[i].y < points[left_point].y) { left_point = i; } } convex_hull.push(points[left_point].clone()); let mut p = left_point; loop { // Find the next counter-clockwise point. let mut next_p = (p + 1) % points.len(); for i in 0..points.len() { let orientation = points[p].consecutive_orientation(&points[i], &points[next_p]); if orientation > 0.0 { next_p = i; } } if next_p == left_point { // Completed constructing the hull. Exit the loop. break; } p = next_p; let last = convex_hull.len() - 1; if convex_hull.len() > 1 && Segment::from_points(points[p].clone(), convex_hull[last - 1].clone()) .on_segment(&convex_hull[last]) { // If the last point lies on the segment with the new point and the second to last // point, we can remove the last point from the hull. convex_hull[last] = points[p].clone(); } else { convex_hull.push(points[p].clone()); } } if convex_hull.len() <= 2 { return vec![]; } let last = convex_hull.len() - 1; if Segment::from_points(convex_hull[0].clone(), convex_hull[last - 1].clone()) .on_segment(&convex_hull[last]) { // Check for the edge case where the last point lies on the segment with the zero'th and // second the last point. In this case, we remove the last point from the hull. convex_hull.pop(); if convex_hull.len() == 2 { return vec![]; } } convex_hull } #[cfg(test)] mod tests { use super::jarvis_march; use super::Point; fn test_jarvis(convex_hull: Vec<Point>, others: Vec<Point>) { let mut points = others.clone(); points.append(&mut convex_hull.clone()); let jarvis = jarvis_march(points); for point in convex_hull { assert!(jarvis.contains(&point)); } for point in others { assert!(!jarvis.contains(&point)); } } #[test] fn too_few_points() { test_jarvis(vec![], vec![]); test_jarvis(vec![], vec![Point::new(0.0, 0.0)]); } #[test] fn duplicate_point() { let p = Point::new(0.0, 0.0); test_jarvis(vec![], vec![p.clone(), p.clone(), p.clone(), p.clone(), p]); } #[test] fn points_same_line() { let p1 = Point::new(1.0, 0.0); let p2 = Point::new(2.0, 0.0); let p3 = Point::new(3.0, 0.0); let p4 = Point::new(4.0, 0.0); let p5 = Point::new(5.0, 0.0); // let p6 = Point::new(1.0, 1.0); test_jarvis(vec![], vec![p1, p2, p3, p4, p5]); } #[test] fn triangle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(1.5, 2.0); let points = vec![p1, p2, p3]; test_jarvis(points, vec![]); } #[test] fn rectangle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let points = vec![p1, p2, p3, p4]; test_jarvis(points, vec![]); } #[test] fn triangle_with_points_in_middle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(1.5, 2.0); let p4 = Point::new(1.5, 1.5); let p5 = Point::new(1.2, 1.3); let p6 = Point::new(1.8, 1.2); let p7 = Point::new(1.5, 1.9); let hull = vec![p1, p2, p3]; let others = vec![p4, p5, p6, p7]; test_jarvis(hull, others); } #[test] fn rectangle_with_points_in_middle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let p5 = Point::new(1.5, 1.5); let p6 = Point::new(1.2, 1.3); let p7 = Point::new(1.8, 1.2); let p8 = Point::new(1.9, 1.7); let p9 = Point::new(1.4, 1.9); let hull = vec![p1, p2, p3, p4]; let others = vec![p5, p6, p7, p8, p9]; test_jarvis(hull, others); } #[test] fn star() { // A single stroke star shape (kind of). Only the tips(p1-5) are part of the convex hull. The // other points would create angles >180 degrees if they were part of the polygon. let p1 = Point::new(-5.0, 6.0); let p2 = Point::new(-11.0, 0.0); let p3 = Point::new(-9.0, -8.0); let p4 = Point::new(4.0, 4.0); let p5 = Point::new(6.0, -7.0); let p6 = Point::new(-7.0, -2.0); let p7 = Point::new(-2.0, -4.0); let p8 = Point::new(0.0, 1.0); let p9 = Point::new(1.0, 0.0); let p10 = Point::new(-6.0, 1.0); let hull = vec![p1, p2, p3, p4, p5]; let others = vec![p6, p7, p8, p9, p10]; test_jarvis(hull, others); } #[test] fn rectangle_with_points_on_same_line() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let p5 = Point::new(1.5, 1.0); let p6 = Point::new(1.0, 1.5); let p7 = Point::new(2.0, 1.5); let p8 = Point::new(1.5, 2.0); let hull = vec![p1, p2, p3, p4]; let others = vec![p5, p6, p7, p8]; test_jarvis(hull, others); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/ramer_douglas_peucker.rs
src/geometry/ramer_douglas_peucker.rs
use crate::geometry::Point; pub fn ramer_douglas_peucker(points: &[Point], epsilon: f64) -> Vec<Point> { if points.len() < 3 { return points.to_vec(); } let mut dmax = 0.0; let mut index = 0; let end = points.len() - 1; for i in 1..end { let d = perpendicular_distance(&points[i], &points[0], &points[end]); if d > dmax { index = i; dmax = d; } } if dmax > epsilon { let mut results = ramer_douglas_peucker(&points[..=index], epsilon); results.pop(); results.extend(ramer_douglas_peucker(&points[index..], epsilon)); results } else { vec![points[0].clone(), points[end].clone()] } } fn perpendicular_distance(p: &Point, a: &Point, b: &Point) -> f64 { let num = (b.y - a.y) * p.x - (b.x - a.x) * p.y + b.x * a.y - b.y * a.x; let den = a.euclidean_distance(b); num.abs() / den } #[cfg(test)] mod tests { use super::*; macro_rules! test_perpendicular_distance { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (p, a, b, expected) = $test_case; assert_eq!(perpendicular_distance(&p, &a, &b), expected); assert_eq!(perpendicular_distance(&p, &b, &a), expected); } )* }; } test_perpendicular_distance! { basic: (Point::new(4.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 3.0), 4.0), basic_shifted_1: (Point::new(4.0, 1.0), Point::new(0.0, 1.0), Point::new(0.0, 4.0), 4.0), basic_shifted_2: (Point::new(2.0, 1.0), Point::new(-2.0, 1.0), Point::new(-2.0, 4.0), 4.0), } #[test] fn test_ramer_douglas_peucker_polygon() { let a = Point::new(0.0, 0.0); let b = Point::new(1.0, 0.0); let c = Point::new(2.0, 0.0); let d = Point::new(2.0, 1.0); let e = Point::new(2.0, 2.0); let f = Point::new(1.0, 2.0); let g = Point::new(0.0, 2.0); let h = Point::new(0.0, 1.0); let polygon = vec![ a.clone(), b, c.clone(), d, e.clone(), f, g.clone(), h.clone(), ]; let epsilon = 0.7; let result = ramer_douglas_peucker(&polygon, epsilon); assert_eq!(result, vec![a, c, e, g, h]); } #[test] fn test_ramer_douglas_peucker_polygonal_chain() { let a = Point::new(0., 0.); let b = Point::new(2., 0.5); let c = Point::new(3., 3.); let d = Point::new(6., 3.); let e = Point::new(8., 4.); let points = vec![a.clone(), b, c, d, e.clone()]; let epsilon = 3.; // The epsilon is quite large, so the result will be a single line let result = ramer_douglas_peucker(&points, epsilon); assert_eq!(result, vec![a, e]); } #[test] fn test_less_than_three_points() { let a = Point::new(0., 0.); let b = Point::new(1., 1.); let epsilon = 0.1; assert_eq!(ramer_douglas_peucker(&[], epsilon), vec![]); assert_eq!( ramer_douglas_peucker(std::slice::from_ref(&a), epsilon), vec![a.clone()] ); assert_eq!( ramer_douglas_peucker(&[a.clone(), b.clone()], epsilon), vec![a, b] ); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/segment.rs
src/geometry/segment.rs
use super::Point; const TOLERANCE: f64 = 0.0001; pub struct Segment { pub a: Point, pub b: Point, } impl Segment { pub fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Segment { Segment { a: Point::new(x1, y1), b: Point::new(x2, y2), } } pub fn from_points(a: Point, b: Point) -> Segment { Segment { a, b } } pub fn direction(&self, p: &Point) -> f64 { let a = Point::new(p.x - self.a.x, p.y - self.a.y); let b = Point::new(self.b.x - self.a.x, self.b.y - self.a.y); a.cross_prod(&b) } pub fn is_vertical(&self) -> bool { self.a.x == self.b.x } // returns (slope, y-intercept) pub fn get_line_equation(&self) -> (f64, f64) { let slope = (self.a.y - self.b.y) / (self.a.x - self.b.x); let y_intercept = self.a.y - slope * self.a.x; (slope, y_intercept) } // Compute the value of y at x. Uses the line equation, and assumes the segment // has infinite length. pub fn compute_y_at_x(&self, x: f64) -> f64 { let (slope, y_intercept) = self.get_line_equation(); slope * x + y_intercept } pub fn is_colinear(&self, p: &Point) -> bool { if self.is_vertical() { p.x == self.a.x } else { (self.compute_y_at_x(p.x) - p.y).abs() < TOLERANCE } } // p must be colinear with the segment pub fn colinear_point_on_segment(&self, p: &Point) -> bool { assert!(self.is_colinear(p), "p must be colinear!"); let (low_x, high_x) = if self.a.x < self.b.x { (self.a.x, self.b.x) } else { (self.b.x, self.a.x) }; let (low_y, high_y) = if self.a.y < self.b.y { (self.a.y, self.b.y) } else { (self.b.y, self.a.y) }; p.x >= low_x && p.x <= high_x && p.y >= low_y && p.y <= high_y } pub fn on_segment(&self, p: &Point) -> bool { if !self.is_colinear(p) { return false; } self.colinear_point_on_segment(p) } pub fn intersects(&self, other: &Segment) -> bool { let direction1 = self.direction(&other.a); let direction2 = self.direction(&other.b); let direction3 = other.direction(&self.a); let direction4 = other.direction(&self.b); // If the segments saddle each others' endpoints, they intersect if ((direction1 > 0.0 && direction2 < 0.0) || (direction1 < 0.0 && direction2 > 0.0)) && ((direction3 > 0.0 && direction4 < 0.0) || (direction3 < 0.0 && direction4 > 0.0)) { return true; } // Edge cases where an endpoint lies on a segment (direction1 == 0.0 && self.colinear_point_on_segment(&other.a)) || (direction2 == 0.0 && self.colinear_point_on_segment(&other.b)) || (direction3 == 0.0 && other.colinear_point_on_segment(&self.a)) || (direction4 == 0.0 && other.colinear_point_on_segment(&self.b)) } } #[cfg(test)] mod tests { use super::Point; use super::Segment; #[test] fn colinear() { let segment = Segment::new(2.0, 3.0, 6.0, 5.0); assert_eq!((0.5, 2.0), segment.get_line_equation()); assert!(segment.is_colinear(&Point::new(2.0, 3.0))); assert!(segment.is_colinear(&Point::new(6.0, 5.0))); assert!(segment.is_colinear(&Point::new(0.0, 2.0))); assert!(segment.is_colinear(&Point::new(-5.0, -0.5))); assert!(segment.is_colinear(&Point::new(10.0, 7.0))); assert!(!segment.is_colinear(&Point::new(0.0, 0.0))); assert!(!segment.is_colinear(&Point::new(1.9, 3.0))); assert!(!segment.is_colinear(&Point::new(2.1, 3.0))); assert!(!segment.is_colinear(&Point::new(2.0, 2.9))); assert!(!segment.is_colinear(&Point::new(2.0, 3.1))); assert!(!segment.is_colinear(&Point::new(5.9, 5.0))); assert!(!segment.is_colinear(&Point::new(6.1, 5.0))); assert!(!segment.is_colinear(&Point::new(6.0, 4.9))); assert!(!segment.is_colinear(&Point::new(6.0, 5.1))); } #[test] fn colinear_vertical() { let segment = Segment::new(2.0, 3.0, 2.0, 5.0); assert!(segment.is_colinear(&Point::new(2.0, 1.0))); assert!(segment.is_colinear(&Point::new(2.0, 3.0))); assert!(segment.is_colinear(&Point::new(2.0, 4.0))); assert!(segment.is_colinear(&Point::new(2.0, 5.0))); assert!(segment.is_colinear(&Point::new(2.0, 6.0))); assert!(!segment.is_colinear(&Point::new(1.0, 3.0))); assert!(!segment.is_colinear(&Point::new(3.0, 3.0))); } fn test_intersect(s1: &Segment, s2: &Segment, result: bool) { assert_eq!(s1.intersects(s2), result); assert_eq!(s2.intersects(s1), result); } #[test] fn intersects() { let s1 = Segment::new(2.0, 3.0, 6.0, 5.0); let s2 = Segment::new(-1.0, 9.0, 10.0, -3.0); let s3 = Segment::new(-0.0, 10.0, 11.0, -2.0); let s4 = Segment::new(100.0, 200.0, 40.0, 50.0); test_intersect(&s1, &s2, true); test_intersect(&s1, &s3, true); test_intersect(&s2, &s3, false); test_intersect(&s1, &s4, false); test_intersect(&s2, &s4, false); test_intersect(&s3, &s4, false); } #[test] fn intersects_endpoint_on_segment() { let s1 = Segment::new(2.0, 3.0, 6.0, 5.0); let s2 = Segment::new(4.0, 4.0, -11.0, 20.0); let s3 = Segment::new(4.0, 4.0, 14.0, -19.0); test_intersect(&s1, &s2, true); test_intersect(&s1, &s3, true); } #[test] fn intersects_self() { let s1 = Segment::new(2.0, 3.0, 6.0, 5.0); let s2 = Segment::new(2.0, 3.0, 6.0, 5.0); test_intersect(&s1, &s2, true); } #[test] fn too_short_to_intersect() { let s1 = Segment::new(2.0, 3.0, 6.0, 5.0); let s2 = Segment::new(-1.0, 10.0, 3.0, 5.0); let s3 = Segment::new(5.0, 3.0, 10.0, -11.0); test_intersect(&s1, &s2, false); test_intersect(&s1, &s3, false); test_intersect(&s2, &s3, false); } #[test] fn parallel_segments() { let s1 = Segment::new(-5.0, 0.0, 5.0, 0.0); let s2 = Segment::new(-5.0, 1.0, 5.0, 1.0); let s3 = Segment::new(-5.0, -1.0, 5.0, -1.0); test_intersect(&s1, &s2, false); test_intersect(&s1, &s3, false); test_intersect(&s2, &s3, false); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/graham_scan.rs
src/geometry/graham_scan.rs
use crate::geometry::Point; use std::cmp::Ordering; fn point_min(a: &&Point, b: &&Point) -> Ordering { // Find the bottom-most point. In the case of a tie, find the left-most. if a.y == b.y { a.x.partial_cmp(&b.x).unwrap() } else { a.y.partial_cmp(&b.y).unwrap() } } // Returns a Vec of Points that make up the convex hull of `points`. Returns an empty Vec if there // is no convex hull. pub fn graham_scan(mut points: Vec<Point>) -> Vec<Point> { if points.len() <= 2 { return vec![]; } let min_point = points.iter().min_by(point_min).unwrap().clone(); points.retain(|p| p != &min_point); if points.is_empty() { // edge case where all the points are the same return vec![]; } let point_cmp = |a: &Point, b: &Point| -> Ordering { // Sort points in counter-clockwise direction relative to the min point. We can this by // checking the orientation of consecutive vectors (min_point, a) and (a, b). let orientation = min_point.consecutive_orientation(a, b); if orientation < 0.0 { Ordering::Greater } else if orientation > 0.0 { Ordering::Less } else { let a_dist = min_point.euclidean_distance(a); let b_dist = min_point.euclidean_distance(b); // When two points have the same relative angle to the min point, we should only // include the further point in the convex hull. We sort further points into a lower // index, and in the algorithm, remove all consecutive points with the same relative // angle. b_dist.partial_cmp(&a_dist).unwrap() } }; points.sort_by(point_cmp); let mut convex_hull: Vec<Point> = vec![]; // We always add the min_point, and the first two points in the sorted vec. convex_hull.push(min_point.clone()); convex_hull.push(points[0].clone()); let mut top = 1; for point in points.iter().skip(1) { if min_point.consecutive_orientation(point, &convex_hull[top]) == 0.0 { // Remove consecutive points with the same angle. We make sure include the furthest // point in the convex hull in the sort comparator. continue; } loop { // In this loop, we remove points that we determine are no longer part of the convex // hull. if top <= 1 { break; } // If there is a segment(i+1, i+2) turns right relative to segment(i, i+1), point(i+1) // is not part of the convex hull. let orientation = convex_hull[top - 1].consecutive_orientation(&convex_hull[top], point); if orientation <= 0.0 { top -= 1; convex_hull.pop(); } else { break; } } convex_hull.push(point.clone()); top += 1; } if convex_hull.len() <= 2 { return vec![]; } convex_hull } #[cfg(test)] mod tests { use super::graham_scan; use super::Point; fn test_graham(convex_hull: Vec<Point>, others: Vec<Point>) { let mut points = convex_hull.clone(); points.append(&mut others.clone()); let graham = graham_scan(points); for point in convex_hull { assert!(graham.contains(&point)); } for point in others { assert!(!graham.contains(&point)); } } #[test] fn too_few_points() { test_graham(vec![], vec![]); test_graham(vec![], vec![Point::new(0.0, 0.0)]); } #[test] fn duplicate_point() { let p = Point::new(0.0, 0.0); test_graham(vec![], vec![p.clone(), p.clone(), p.clone(), p.clone(), p]); } #[test] fn points_same_line() { let p1 = Point::new(1.0, 0.0); let p2 = Point::new(2.0, 0.0); let p3 = Point::new(3.0, 0.0); let p4 = Point::new(4.0, 0.0); let p5 = Point::new(5.0, 0.0); // let p6 = Point::new(1.0, 1.0); test_graham(vec![], vec![p1, p2, p3, p4, p5]); } #[test] fn triangle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(1.5, 2.0); let points = vec![p1, p2, p3]; test_graham(points, vec![]); } #[test] fn rectangle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let points = vec![p1, p2, p3, p4]; test_graham(points, vec![]); } #[test] fn triangle_with_points_in_middle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(1.5, 2.0); let p4 = Point::new(1.5, 1.5); let p5 = Point::new(1.2, 1.3); let p6 = Point::new(1.8, 1.2); let p7 = Point::new(1.5, 1.9); let hull = vec![p1, p2, p3]; let others = vec![p4, p5, p6, p7]; test_graham(hull, others); } #[test] fn rectangle_with_points_in_middle() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let p5 = Point::new(1.5, 1.5); let p6 = Point::new(1.2, 1.3); let p7 = Point::new(1.8, 1.2); let p8 = Point::new(1.9, 1.7); let p9 = Point::new(1.4, 1.9); let hull = vec![p1, p2, p3, p4]; let others = vec![p5, p6, p7, p8, p9]; test_graham(hull, others); } #[test] fn star() { // A single stroke star shape (kind of). Only the tips(p1-5) are part of the convex hull. The // other points would create angles >180 degrees if they were part of the polygon. let p1 = Point::new(-5.0, 6.0); let p2 = Point::new(-11.0, 0.0); let p3 = Point::new(-9.0, -8.0); let p4 = Point::new(4.0, 4.0); let p5 = Point::new(6.0, -7.0); let p6 = Point::new(-7.0, -2.0); let p7 = Point::new(-2.0, -4.0); let p8 = Point::new(0.0, 1.0); let p9 = Point::new(1.0, 0.0); let p10 = Point::new(-6.0, 1.0); let hull = vec![p1, p2, p3, p4, p5]; let others = vec![p6, p7, p8, p9, p10]; test_graham(hull, others); } #[test] fn rectangle_with_points_on_same_line() { let p1 = Point::new(1.0, 1.0); let p2 = Point::new(2.0, 1.0); let p3 = Point::new(2.0, 2.0); let p4 = Point::new(1.0, 2.0); let p5 = Point::new(1.5, 1.0); let p6 = Point::new(1.0, 1.5); let p7 = Point::new(2.0, 1.5); let p8 = Point::new(1.5, 2.0); let hull = vec![p1, p2, p3, p4]; let others = vec![p5, p6, p7, p8]; test_graham(hull, others); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/geometry/point.rs
src/geometry/point.rs
use std::ops::Sub; #[derive(Clone, Debug, PartialEq)] pub struct Point { pub x: f64, pub y: f64, } impl Point { pub fn new(x: f64, y: f64) -> Point { Point { x, y } } // Returns the orientation of consecutive segments ab and bc. pub fn consecutive_orientation(&self, b: &Point, c: &Point) -> f64 { let p1 = b - self; let p2 = c - self; p1.cross_prod(&p2) } pub fn cross_prod(&self, other: &Point) -> f64 { self.x * other.y - self.y * other.x } pub fn euclidean_distance(&self, other: &Point) -> f64 { ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt() } } impl Sub for &Point { type Output = Point; fn sub(self, other: Self) -> Point { let x = self.x - other.x; let y = self.y - other.y; Point::new(x, y) } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/jump_search.rs
src/searching/jump_search.rs
use std::cmp::min; pub fn jump_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> { let len = arr.len(); if len == 0 { return None; } let mut step = (len as f64).sqrt() as usize; let mut prev = 0; while &arr[min(len, step) - 1] < item { prev = step; step += (len as f64).sqrt() as usize; if prev >= len { return None; } } while &arr[prev] < item { prev += 1; } if &arr[prev] == item { return Some(prev); } None } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { assert!(jump_search(&"a", &[]).is_none()); } #[test] fn one_item() { assert_eq!(jump_search(&"a", &["a"]).unwrap(), 0); } #[test] fn search_strings() { assert_eq!( jump_search(&"a", &["a", "b", "c", "d", "google", "zoo"]).unwrap(), 0 ); } #[test] fn search_ints() { let arr = [1, 2, 3, 4]; assert_eq!(jump_search(&4, &arr).unwrap(), 3); assert_eq!(jump_search(&3, &arr).unwrap(), 2); assert_eq!(jump_search(&2, &arr).unwrap(), 1); assert_eq!(jump_search(&1, &arr).unwrap(), 0); } #[test] fn not_found() { let arr = [1, 2, 3, 4]; assert!(jump_search(&5, &arr).is_none()); assert!(jump_search(&0, &arr).is_none()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/binary_search.rs
src/searching/binary_search.rs
//! This module provides an implementation of a binary search algorithm that //! works for both ascending and descending ordered arrays. The binary search //! function returns the index of the target element if it is found, or `None` //! if the target is not present in the array. use std::cmp::Ordering; /// Performs a binary search for a specified item within a sorted array. /// /// This function can handle both ascending and descending ordered arrays. It /// takes a reference to the item to search for and a slice of the array. If /// the item is found, it returns the index of the item within the array. If /// the item is not found, it returns `None`. /// /// # Parameters /// /// - `item`: A reference to the item to search for. /// - `arr`: A slice of the sorted array in which to search. /// /// # Returns /// /// An `Option<usize>` which is: /// - `Some(index)` if the item is found at the given index. /// - `None` if the item is not found in the array. pub fn binary_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> { let is_asc = is_asc_arr(arr); let mut left = 0; let mut right = arr.len(); while left < right { if match_compare(item, arr, &mut left, &mut right, is_asc) { return Some(left); } } None } /// Compares the item with the middle element of the current search range and /// updates the search bounds accordingly. This function handles both ascending /// and descending ordered arrays. It calculates the middle index of the /// current search range and compares the item with the element at /// this index. It then updates the search bounds (`left` and `right`) based on /// the result of this comparison. If the item is found, it updates `left` to /// the index of the found item and returns `true`. /// /// # Parameters /// /// - `item`: A reference to the item to search for. /// - `arr`: A slice of the array in which to search. /// - `left`: A mutable reference to the left bound of the search range. /// - `right`: A mutable reference to the right bound of the search range. /// - `is_asc`: A boolean indicating whether the array is sorted in ascending order. /// /// # Returns /// /// A `bool` indicating whether the item was found. fn match_compare<T: Ord>( item: &T, arr: &[T], left: &mut usize, right: &mut usize, is_asc: bool, ) -> bool { let mid = *left + (*right - *left) / 2; let cmp_result = item.cmp(&arr[mid]); match (is_asc, cmp_result) { (true, Ordering::Less) | (false, Ordering::Greater) => { *right = mid; } (true, Ordering::Greater) | (false, Ordering::Less) => { *left = mid + 1; } (_, Ordering::Equal) => { *left = mid; return true; } } false } /// Determines if the given array is sorted in ascending order. /// /// This helper function checks if the first element of the array is less than the /// last element, indicating an ascending order. It returns `false` if the array /// has fewer than two elements. /// /// # Parameters /// /// - `arr`: A slice of the array to check. /// /// # Returns /// /// A `bool` indicating whether the array is sorted in ascending order. fn is_asc_arr<T: Ord>(arr: &[T]) -> bool { arr.len() > 1 && arr[0] < arr[arr.len() - 1] } #[cfg(test)] mod tests { use super::*; macro_rules! test_cases { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (item, arr, expected) = $test_case; assert_eq!(binary_search(&item, arr), expected); } )* }; } test_cases! { empty: ("a", &[] as &[&str], None), one_item_found: ("a", &["a"], Some(0)), one_item_not_found: ("b", &["a"], None), search_strings_asc_start: ("a", &["a", "b", "c", "d", "google", "zoo"], Some(0)), search_strings_asc_middle: ("google", &["a", "b", "c", "d", "google", "zoo"], Some(4)), search_strings_asc_last: ("zoo", &["a", "b", "c", "d", "google", "zoo"], Some(5)), search_strings_asc_not_found: ("x", &["a", "b", "c", "d", "google", "zoo"], None), search_strings_desc_start: ("zoo", &["zoo", "google", "d", "c", "b", "a"], Some(0)), search_strings_desc_middle: ("google", &["zoo", "google", "d", "c", "b", "a"], Some(1)), search_strings_desc_last: ("a", &["zoo", "google", "d", "c", "b", "a"], Some(5)), search_strings_desc_not_found: ("x", &["zoo", "google", "d", "c", "b", "a"], None), search_ints_asc_start: (1, &[1, 2, 3, 4], Some(0)), search_ints_asc_middle: (3, &[1, 2, 3, 4], Some(2)), search_ints_asc_end: (4, &[1, 2, 3, 4], Some(3)), search_ints_asc_not_found: (5, &[1, 2, 3, 4], None), search_ints_desc_start: (4, &[4, 3, 2, 1], Some(0)), search_ints_desc_middle: (3, &[4, 3, 2, 1], Some(1)), search_ints_desc_end: (1, &[4, 3, 2, 1], Some(3)), search_ints_desc_not_found: (5, &[4, 3, 2, 1], None), with_gaps_0: (0, &[1, 3, 8, 11], None), with_gaps_1: (1, &[1, 3, 8, 11], Some(0)), with_gaps_2: (2, &[1, 3, 8, 11], None), with_gaps_3: (3, &[1, 3, 8, 11], Some(1)), with_gaps_4: (4, &[1, 3, 8, 10], None), with_gaps_5: (5, &[1, 3, 8, 10], None), with_gaps_6: (6, &[1, 3, 8, 10], None), with_gaps_7: (7, &[1, 3, 8, 11], None), with_gaps_8: (8, &[1, 3, 8, 11], Some(2)), with_gaps_9: (9, &[1, 3, 8, 11], None), with_gaps_10: (10, &[1, 3, 8, 11], None), with_gaps_11: (11, &[1, 3, 8, 11], Some(3)), with_gaps_12: (12, &[1, 3, 8, 11], None), with_gaps_13: (13, &[1, 3, 8, 11], None), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/quick_select.rs
src/searching/quick_select.rs
// https://en.wikipedia.org/wiki/Quickselect fn partition(list: &mut [i32], left: usize, right: usize, pivot_index: usize) -> usize { let pivot_value = list[pivot_index]; list.swap(pivot_index, right); // Move pivot to end let mut store_index = left; for i in left..right { if list[i] < pivot_value { list.swap(store_index, i); store_index += 1; } } list.swap(right, store_index); // Move pivot to its final place store_index } pub fn quick_select(list: &mut [i32], left: usize, right: usize, index: usize) -> i32 { if left == right { // If the list contains only one element, return list[left]; } // return that element let mut pivot_index = left + (right - left) / 2; // select a pivotIndex between left and right pivot_index = partition(list, left, right, pivot_index); // The pivot is in its final sorted position match index { x if x == pivot_index => list[index], x if x < pivot_index => quick_select(list, left, pivot_index - 1, index), _ => quick_select(list, pivot_index + 1, right, index), } } #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { let mut arr1 = [2, 3, 4, 5]; assert_eq!(quick_select(&mut arr1, 0, 3, 1), 3); let mut arr2 = [2, 5, 9, 12, 16]; assert_eq!(quick_select(&mut arr2, 1, 3, 2), 9); let mut arr2 = [0, 3, 8]; assert_eq!(quick_select(&mut arr2, 0, 0, 0), 0); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/saddleback_search.rs
src/searching/saddleback_search.rs
// Saddleback search is a technique used to find an element in a sorted 2D matrix in O(m + n) time, // where m is the number of rows, and n is the number of columns. It works by starting from the // top-right corner of the matrix and moving left or down based on the comparison of the current // element with the target element. use std::cmp::Ordering; pub fn saddleback_search(matrix: &[Vec<i32>], element: i32) -> (usize, usize) { // Initialize left and right indices let mut left_index = 0; let mut right_index = matrix[0].len() - 1; // Start searching while left_index < matrix.len() { match element.cmp(&matrix[left_index][right_index]) { // If the current element matches the target element, return its position (indices are 1-based) Ordering::Equal => return (left_index + 1, right_index + 1), Ordering::Greater => { // If the target element is greater, move to the next row (downwards) left_index += 1; } Ordering::Less => { // If the target element is smaller, move to the previous column (leftwards) if right_index == 0 { break; // If we reach the left-most column, exit the loop } right_index -= 1; } } } // If the element is not found, return (0, 0) (0, 0) } #[cfg(test)] mod tests { use super::*; // Test when the element is not present in the matrix #[test] fn test_element_not_found() { let matrix = vec![vec![1, 10, 100], vec![2, 20, 200], vec![3, 30, 300]]; assert_eq!(saddleback_search(&matrix, 123), (0, 0)); } // Test when the element is at the top-left corner of the matrix #[test] fn test_element_at_top_left() { let matrix = vec![vec![1, 10, 100], vec![2, 20, 200], vec![3, 30, 300]]; assert_eq!(saddleback_search(&matrix, 1), (1, 1)); } // Test when the element is at the bottom-right corner of the matrix #[test] fn test_element_at_bottom_right() { let matrix = vec![vec![1, 10, 100], vec![2, 20, 200], vec![3, 30, 300]]; assert_eq!(saddleback_search(&matrix, 300), (3, 3)); } // Test when the element is at the top-right corner of the matrix #[test] fn test_element_at_top_right() { let matrix = vec![vec![1, 10, 100], vec![2, 20, 200], vec![3, 30, 300]]; assert_eq!(saddleback_search(&matrix, 100), (1, 3)); } // Test when the element is at the bottom-left corner of the matrix #[test] fn test_element_at_bottom_left() { let matrix = vec![vec![1, 10, 100], vec![2, 20, 200], vec![3, 30, 300]]; assert_eq!(saddleback_search(&matrix, 3), (3, 1)); } // Additional test case: Element in the middle of the matrix #[test] fn test_element_in_middle() { let matrix = vec![ vec![1, 10, 100, 1000], vec![2, 20, 200, 2000], vec![3, 30, 300, 3000], ]; assert_eq!(saddleback_search(&matrix, 200), (2, 3)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/binary_search_recursive.rs
src/searching/binary_search_recursive.rs
use std::cmp::Ordering; /// Recursively performs a binary search for a specified item within a sorted array. /// /// This function can handle both ascending and descending ordered arrays. It /// takes a reference to the item to search for and a slice of the array. If /// the item is found, it returns the index of the item within the array. If /// the item is not found, it returns `None`. /// /// # Parameters /// /// - `item`: A reference to the item to search for. /// - `arr`: A slice of the sorted array in which to search. /// - `left`: The left bound of the current search range. /// - `right`: The right bound of the current search range. /// - `is_asc`: A boolean indicating whether the array is sorted in ascending order. /// /// # Returns /// /// An `Option<usize>` which is: /// - `Some(index)` if the item is found at the given index. /// - `None` if the item is not found in the array. pub fn binary_search_rec<T: Ord>(item: &T, arr: &[T], left: usize, right: usize) -> Option<usize> { if left >= right { return None; } let is_asc = arr.len() > 1 && arr[0] < arr[arr.len() - 1]; let mid = left + (right - left) / 2; let cmp_result = item.cmp(&arr[mid]); match (is_asc, cmp_result) { (true, Ordering::Less) | (false, Ordering::Greater) => { binary_search_rec(item, arr, left, mid) } (true, Ordering::Greater) | (false, Ordering::Less) => { binary_search_rec(item, arr, mid + 1, right) } (_, Ordering::Equal) => Some(mid), } } #[cfg(test)] mod tests { use super::*; macro_rules! test_cases { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (item, arr, expected) = $test_case; assert_eq!(binary_search_rec(&item, arr, 0, arr.len()), expected); } )* }; } test_cases! { empty: ("a", &[] as &[&str], None), one_item_found: ("a", &["a"], Some(0)), one_item_not_found: ("b", &["a"], None), search_strings_asc_start: ("a", &["a", "b", "c", "d", "google", "zoo"], Some(0)), search_strings_asc_middle: ("google", &["a", "b", "c", "d", "google", "zoo"], Some(4)), search_strings_asc_last: ("zoo", &["a", "b", "c", "d", "google", "zoo"], Some(5)), search_strings_asc_not_found: ("x", &["a", "b", "c", "d", "google", "zoo"], None), search_strings_desc_start: ("zoo", &["zoo", "google", "d", "c", "b", "a"], Some(0)), search_strings_desc_middle: ("google", &["zoo", "google", "d", "c", "b", "a"], Some(1)), search_strings_desc_last: ("a", &["zoo", "google", "d", "c", "b", "a"], Some(5)), search_strings_desc_not_found: ("x", &["zoo", "google", "d", "c", "b", "a"], None), search_ints_asc_start: (1, &[1, 2, 3, 4], Some(0)), search_ints_asc_middle: (3, &[1, 2, 3, 4], Some(2)), search_ints_asc_end: (4, &[1, 2, 3, 4], Some(3)), search_ints_asc_not_found: (5, &[1, 2, 3, 4], None), search_ints_desc_start: (4, &[4, 3, 2, 1], Some(0)), search_ints_desc_middle: (3, &[4, 3, 2, 1], Some(1)), search_ints_desc_end: (1, &[4, 3, 2, 1], Some(3)), search_ints_desc_not_found: (5, &[4, 3, 2, 1], None), with_gaps_0: (0, &[1, 3, 8, 11], None), with_gaps_1: (1, &[1, 3, 8, 11], Some(0)), with_gaps_2: (2, &[1, 3, 8, 11], None), with_gaps_3: (3, &[1, 3, 8, 11], Some(1)), with_gaps_4: (4, &[1, 3, 8, 10], None), with_gaps_5: (5, &[1, 3, 8, 10], None), with_gaps_6: (6, &[1, 3, 8, 10], None), with_gaps_7: (7, &[1, 3, 8, 11], None), with_gaps_8: (8, &[1, 3, 8, 11], Some(2)), with_gaps_9: (9, &[1, 3, 8, 11], None), with_gaps_10: (10, &[1, 3, 8, 11], None), with_gaps_11: (11, &[1, 3, 8, 11], Some(3)), with_gaps_12: (12, &[1, 3, 8, 11], None), with_gaps_13: (13, &[1, 3, 8, 11], None), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/ternary_search_min_max_recursive.rs
src/searching/ternary_search_min_max_recursive.rs
/// Recursive ternary search algorithm for finding maximum of unimodal function pub fn ternary_search_max_rec( f: fn(f32) -> f32, start: f32, end: f32, absolute_precision: f32, ) -> f32 { if (end - start).abs() >= absolute_precision { let mid1 = start + (end - start) / 3.0; let mid2 = end - (end - start) / 3.0; let r1 = f(mid1); let r2 = f(mid2); if r1 < r2 { return ternary_search_max_rec(f, mid1, end, absolute_precision); } else if r1 > r2 { return ternary_search_max_rec(f, start, mid2, absolute_precision); } return ternary_search_max_rec(f, mid1, mid2, absolute_precision); } f(start) } /// Recursive ternary search algorithm for finding minimum of unimodal function pub fn ternary_search_min_rec( f: fn(f32) -> f32, start: f32, end: f32, absolute_precision: f32, ) -> f32 { if (end - start).abs() >= absolute_precision { let mid1 = start + (end - start) / 3.0; let mid2 = end - (end - start) / 3.0; let r1 = f(mid1); let r2 = f(mid2); if r1 < r2 { return ternary_search_min_rec(f, start, mid2, absolute_precision); } else if r1 > r2 { return ternary_search_min_rec(f, mid1, end, absolute_precision); } return ternary_search_min_rec(f, mid1, mid2, absolute_precision); } f(start) } #[cfg(test)] mod tests { use super::*; #[test] fn finds_max_value() { let expected = 4.0; let f = |x: f32| -x * x - 2.0 * x + 3.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.0000001; let result = ternary_search_max_rec(f, start, end, absolute_precision); assert_eq!(result, expected); } #[test] fn finds_min_value() { let expected = 2.0; let f = |x: f32| x * x - 2.0 * x + 3.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.0000001; let result = ternary_search_min_rec(f, start, end, absolute_precision); assert_eq!(result, expected); } #[test] fn finds_max_value_2() { let expected = 7.25; let f = |x: f32| -x.powi(2) + 3.0 * x + 5.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.000001; let result = ternary_search_max_rec(f, start, end, absolute_precision); assert_eq!(result, expected); } #[test] fn finds_min_value_2() { let expected = 2.75; let f = |x: f32| x.powi(2) + 3.0 * x + 5.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.000001; let result = ternary_search_min_rec(f, start, end, absolute_precision); assert_eq!(result, expected); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/mod.rs
src/searching/mod.rs
mod binary_search; mod binary_search_recursive; mod exponential_search; mod fibonacci_search; mod interpolation_search; mod jump_search; mod kth_smallest; mod kth_smallest_heap; mod linear_search; mod moore_voting; mod quick_select; mod saddleback_search; mod ternary_search; mod ternary_search_min_max; mod ternary_search_min_max_recursive; mod ternary_search_recursive; pub use self::binary_search::binary_search; pub use self::binary_search_recursive::binary_search_rec; pub use self::exponential_search::exponential_search; pub use self::fibonacci_search::fibonacci_search; pub use self::interpolation_search::interpolation_search; pub use self::jump_search::jump_search; pub use self::kth_smallest::kth_smallest; pub use self::kth_smallest_heap::kth_smallest_heap; pub use self::linear_search::linear_search; pub use self::moore_voting::moore_voting; pub use self::quick_select::quick_select; pub use self::saddleback_search::saddleback_search; pub use self::ternary_search::ternary_search; pub use self::ternary_search_min_max::ternary_search_max; pub use self::ternary_search_min_max::ternary_search_min; pub use self::ternary_search_min_max_recursive::ternary_search_max_rec; pub use self::ternary_search_min_max_recursive::ternary_search_min_rec; pub use self::ternary_search_recursive::ternary_search_rec;
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/linear_search.rs
src/searching/linear_search.rs
/// Performs a linear search on the given array, returning the index of the first occurrence of the item. /// /// # Arguments /// /// * `item` - A reference to the item to search for in the array. /// * `arr` - A slice of items to search within. /// /// # Returns /// /// * `Some(usize)` - The index of the first occurrence of the item, if found. /// * `None` - If the item is not found in the array. pub fn linear_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> { for (i, data) in arr.iter().enumerate() { if item == data { return Some(i); } } None } #[cfg(test)] mod tests { use super::*; macro_rules! test_cases { ($($name:ident: $tc:expr,)*) => { $( #[test] fn $name() { let (item, arr, expected) = $tc; if let Some(expected_index) = expected { assert_eq!(arr[expected_index], item); } assert_eq!(linear_search(&item, arr), expected); } )* } } test_cases! { empty: ("a", &[] as &[&str], None), one_item_found: ("a", &["a"], Some(0)), one_item_not_found: ("b", &["a"], None), search_strings_asc_start: ("a", &["a", "b", "c", "d", "google", "zoo"], Some(0)), search_strings_asc_middle: ("google", &["a", "b", "c", "d", "google", "zoo"], Some(4)), search_strings_asc_last: ("zoo", &["a", "b", "c", "d", "google", "zoo"], Some(5)), search_strings_asc_not_found: ("x", &["a", "b", "c", "d", "google", "zoo"], None), search_strings_desc_start: ("zoo", &["zoo", "google", "d", "c", "b", "a"], Some(0)), search_strings_desc_middle: ("google", &["zoo", "google", "d", "c", "b", "a"], Some(1)), search_strings_desc_last: ("a", &["zoo", "google", "d", "c", "b", "a"], Some(5)), search_strings_desc_not_found: ("x", &["zoo", "google", "d", "c", "b", "a"], None), search_ints_asc_start: (1, &[1, 2, 3, 4], Some(0)), search_ints_asc_middle: (3, &[1, 2, 3, 4], Some(2)), search_ints_asc_end: (4, &[1, 2, 3, 4], Some(3)), search_ints_asc_not_found: (5, &[1, 2, 3, 4], None), search_ints_desc_start: (4, &[4, 3, 2, 1], Some(0)), search_ints_desc_middle: (3, &[4, 3, 2, 1], Some(1)), search_ints_desc_end: (1, &[4, 3, 2, 1], Some(3)), search_ints_desc_not_found: (5, &[4, 3, 2, 1], None), with_gaps_0: (0, &[1, 3, 8, 11], None), with_gaps_1: (1, &[1, 3, 8, 11], Some(0)), with_gaps_2: (2, &[1, 3, 8, 11], None), with_gaps_3: (3, &[1, 3, 8, 11], Some(1)), with_gaps_4: (4, &[1, 3, 8, 10], None), with_gaps_5: (5, &[1, 3, 8, 10], None), with_gaps_6: (6, &[1, 3, 8, 10], None), with_gaps_7: (7, &[1, 3, 8, 11], None), with_gaps_8: (8, &[1, 3, 8, 11], Some(2)), with_gaps_9: (9, &[1, 3, 8, 11], None), with_gaps_10: (10, &[1, 3, 8, 11], None), with_gaps_11: (11, &[1, 3, 8, 11], Some(3)), with_gaps_12: (12, &[1, 3, 8, 11], None), with_gaps_13: (13, &[1, 3, 8, 11], None), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/ternary_search.rs
src/searching/ternary_search.rs
//! This module provides an implementation of a ternary search algorithm that //! works for both ascending and descending ordered arrays. The ternary search //! function returns the index of the target element if it is found, or `None` //! if the target is not present in the array. use std::cmp::Ordering; /// Performs a ternary search for a specified item within a sorted array. /// /// This function can handle both ascending and descending ordered arrays. It /// takes a reference to the item to search for and a slice of the array. If /// the item is found, it returns the index of the item within the array. If /// the item is not found, it returns `None`. /// /// # Parameters /// /// - `item`: A reference to the item to search for. /// - `arr`: A slice of the sorted array in which to search. /// /// # Returns /// /// An `Option<usize>` which is: /// - `Some(index)` if the item is found at the given index. /// - `None` if the item is not found in the array. pub fn ternary_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> { if arr.is_empty() { return None; } let is_asc = is_asc_arr(arr); let mut left = 0; let mut right = arr.len() - 1; while left <= right { if match_compare(item, arr, &mut left, &mut right, is_asc) { return Some(left); } } None } /// Compares the item with two middle elements of the current search range and /// updates the search bounds accordingly. This function handles both ascending /// and descending ordered arrays. It calculates two middle indices of the /// current search range and compares the item with the elements at these /// indices. It then updates the search bounds (`left` and `right`) based on /// the result of these comparisons. If the item is found, it returns `true`. /// /// # Parameters /// /// - `item`: A reference to the item to search for. /// - `arr`: A slice of the array in which to search. /// - `left`: A mutable reference to the left bound of the search range. /// - `right`: A mutable reference to the right bound of the search range. /// - `is_asc`: A boolean indicating whether the array is sorted in ascending order. /// /// # Returns /// /// A `bool` indicating: /// - `true` if the item was found in the array. /// - `false` if the item was not found in the array. fn match_compare<T: Ord>( item: &T, arr: &[T], left: &mut usize, right: &mut usize, is_asc: bool, ) -> bool { let first_mid = *left + (*right - *left) / 3; let second_mid = *right - (*right - *left) / 3; // Handling the edge case where the search narrows down to a single element if first_mid == second_mid && first_mid == *left { return match &arr[*left] { x if x == item => true, _ => { *left += 1; false } }; } let cmp_first_mid = item.cmp(&arr[first_mid]); let cmp_second_mid = item.cmp(&arr[second_mid]); match (is_asc, cmp_first_mid, cmp_second_mid) { // If the item matches either midpoint, it returns the index (_, Ordering::Equal, _) => { *left = first_mid; return true; } (_, _, Ordering::Equal) => { *left = second_mid; return true; } // If the item is smaller than the element at first_mid (in ascending order) // or greater than it (in descending order), it narrows the search to the first third. (true, Ordering::Less, _) | (false, Ordering::Greater, _) => { *right = first_mid.saturating_sub(1) } // If the item is greater than the element at second_mid (in ascending order) // or smaller than it (in descending order), it narrows the search to the last third. (true, _, Ordering::Greater) | (false, _, Ordering::Less) => *left = second_mid + 1, // Otherwise, it searches the middle third. (_, _, _) => { *left = first_mid + 1; *right = second_mid - 1; } } false } /// Determines if the given array is sorted in ascending order. /// /// This helper function checks if the first element of the array is less than the /// last element, indicating an ascending order. It returns `false` if the array /// has fewer than two elements. /// /// # Parameters /// /// - `arr`: A slice of the array to check. /// /// # Returns /// /// A `bool` indicating whether the array is sorted in ascending order. fn is_asc_arr<T: Ord>(arr: &[T]) -> bool { arr.len() > 1 && arr[0] < arr[arr.len() - 1] } #[cfg(test)] mod tests { use super::*; macro_rules! test_cases { ($($name:ident: $test_case:expr,)*) => { $( #[test] fn $name() { let (item, arr, expected) = $test_case; if let Some(expected_index) = expected { assert_eq!(arr[expected_index], item); } assert_eq!(ternary_search(&item, arr), expected); } )* }; } test_cases! { empty: ("a", &[] as &[&str], None), one_item_found: ("a", &["a"], Some(0)), one_item_not_found: ("b", &["a"], None), search_two_elements_found_at_start: (1, &[1, 2], Some(0)), search_two_elements_found_at_end: (2, &[1, 2], Some(1)), search_two_elements_not_found_start: (0, &[1, 2], None), search_two_elements_not_found_end: (3, &[1, 2], None), search_three_elements_found_start: (1, &[1, 2, 3], Some(0)), search_three_elements_found_middle: (2, &[1, 2, 3], Some(1)), search_three_elements_found_end: (3, &[1, 2, 3], Some(2)), search_three_elements_not_found_start: (0, &[1, 2, 3], None), search_three_elements_not_found_end: (4, &[1, 2, 3], None), search_strings_asc_start: ("a", &["a", "b", "c", "d", "google", "zoo"], Some(0)), search_strings_asc_middle: ("google", &["a", "b", "c", "d", "google", "zoo"], Some(4)), search_strings_asc_last: ("zoo", &["a", "b", "c", "d", "google", "zoo"], Some(5)), search_strings_asc_not_found: ("x", &["a", "b", "c", "d", "google", "zoo"], None), search_strings_desc_start: ("zoo", &["zoo", "google", "d", "c", "b", "a"], Some(0)), search_strings_desc_middle: ("google", &["zoo", "google", "d", "c", "b", "a"], Some(1)), search_strings_desc_last: ("a", &["zoo", "google", "d", "c", "b", "a"], Some(5)), search_strings_desc_not_found: ("x", &["zoo", "google", "d", "c", "b", "a"], None), search_ints_asc_start: (1, &[1, 2, 3, 4], Some(0)), search_ints_asc_middle: (3, &[1, 2, 3, 4], Some(2)), search_ints_asc_end: (4, &[1, 2, 3, 4], Some(3)), search_ints_asc_not_found: (5, &[1, 2, 3, 4], None), search_ints_desc_start: (4, &[4, 3, 2, 1], Some(0)), search_ints_desc_middle: (3, &[4, 3, 2, 1], Some(1)), search_ints_desc_end: (1, &[4, 3, 2, 1], Some(3)), search_ints_desc_not_found: (5, &[4, 3, 2, 1], None), with_gaps_0: (0, &[1, 3, 8, 11], None), with_gaps_1: (1, &[1, 3, 8, 11], Some(0)), with_gaps_2: (2, &[1, 3, 8, 11], None), with_gaps_3: (3, &[1, 3, 8, 11], Some(1)), with_gaps_4: (4, &[1, 3, 8, 10], None), with_gaps_5: (5, &[1, 3, 8, 10], None), with_gaps_6: (6, &[1, 3, 8, 10], None), with_gaps_7: (7, &[1, 3, 8, 11], None), with_gaps_8: (8, &[1, 3, 8, 11], Some(2)), with_gaps_9: (9, &[1, 3, 8, 11], None), with_gaps_10: (10, &[1, 3, 8, 11], None), with_gaps_11: (11, &[1, 3, 8, 11], Some(3)), with_gaps_12: (12, &[1, 3, 8, 11], None), with_gaps_13: (13, &[1, 3, 8, 11], None), } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/ternary_search_recursive.rs
src/searching/ternary_search_recursive.rs
use std::cmp::Ordering; pub fn ternary_search_rec<T: Ord>( target: &T, list: &[T], start: usize, end: usize, ) -> Option<usize> { if list.is_empty() { return None; } if end >= start { let mid1: usize = start + (end - start) / 3; let mid2: usize = end - (end - start) / 3; match target.cmp(&list[mid1]) { Ordering::Less => return ternary_search_rec(target, list, start, mid1 - 1), Ordering::Equal => return Some(mid1), Ordering::Greater => match target.cmp(&list[mid2]) { Ordering::Greater => return ternary_search_rec(target, list, mid2 + 1, end), Ordering::Equal => return Some(mid2), Ordering::Less => return ternary_search_rec(target, list, mid1 + 1, mid2 - 1), }, } } None } #[cfg(test)] mod tests { use super::*; #[test] fn returns_none_if_empty_list() { let index = ternary_search_rec(&"a", &[], 1, 10); assert_eq!(index, None); } #[test] fn returns_none_if_range_is_invalid() { let index = ternary_search_rec(&1, &[1, 2, 3], 2, 1); assert_eq!(index, None); } #[test] fn returns_index_if_list_has_one_item() { let index = ternary_search_rec(&1, &[1], 0, 1); assert_eq!(index, Some(0)); } #[test] fn returns_first_index() { let index = ternary_search_rec(&1, &[1, 2, 3], 0, 2); assert_eq!(index, Some(0)); } #[test] fn returns_first_index_if_end_out_of_bounds() { let index = ternary_search_rec(&1, &[1, 2, 3], 0, 3); assert_eq!(index, Some(0)); } #[test] fn returns_last_index() { let index = ternary_search_rec(&3, &[1, 2, 3], 0, 2); assert_eq!(index, Some(2)); } #[test] fn returns_last_index_if_end_out_of_bounds() { let index = ternary_search_rec(&3, &[1, 2, 3], 0, 3); assert_eq!(index, Some(2)); } #[test] fn returns_middle_index() { let index = ternary_search_rec(&2, &[1, 2, 3], 0, 2); assert_eq!(index, Some(1)); } #[test] fn returns_middle_index_if_end_out_of_bounds() { let index = ternary_search_rec(&2, &[1, 2, 3], 0, 3); assert_eq!(index, Some(1)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/moore_voting.rs
src/searching/moore_voting.rs
/* Moore's voting algorithm finds out the strictly majority-occurring element without using extra space and O(n) + O(n) time complexity It is built on the intuition that a strictly major element will always have a net occurrence as 1. Say, array given: 9 1 8 1 1 Here, the algorithm will work as: (for finding element present >(n/2) times) (assumed: all elements are >0) Initialisation: ele=0, cnt=0 Loop beings. loop 1: arr[0]=9 ele = 9 cnt=1 (since cnt = 0, cnt increments to 1 and ele = 9) loop 2: arr[1]=1 ele = 9 cnt= 0 (since in this turn of the loop, the array[i] != ele, cnt decrements by 1) loop 3: arr[2]=8 ele = 8 cnt=1 (since cnt = 0, cnt increments to 1 and ele = 8) loop 4: arr[3]=1 ele = 8 cnt= 0 (since in this turn of the loop, the array[i] != ele, cnt decrements by 1) loop 5: arr[4]=1 ele = 9 cnt=1 (since cnt = 0, cnt increments to 1 and ele = 1) Now, this ele should be the majority element if there's any To check, a quick O(n) loop is run to check if the count of ele is >(n/2), n being the length of the array -1 is returned when no such element is found. */ pub fn moore_voting(arr: &[i32]) -> i32 { let n = arr.len(); let mut cnt = 0; // initializing cnt let mut ele = 0; // initializing ele for &item in arr.iter() { if cnt == 0 { cnt = 1; ele = item; } else if item == ele { cnt += 1; } else { cnt -= 1; } } let cnt_check = arr.iter().filter(|&&x| x == ele).count(); if cnt_check > (n / 2) { ele } else { -1 } } #[cfg(test)] mod tests { use super::*; #[test] fn test_moore_voting() { let arr1: Vec<i32> = vec![9, 1, 8, 1, 1]; assert!(moore_voting(&arr1) == 1); let arr2: Vec<i32> = vec![1, 2, 3, 4]; assert!(moore_voting(&arr2) == -1); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/kth_smallest_heap.rs
src/searching/kth_smallest_heap.rs
use crate::data_structures::Heap; use std::cmp::{Ord, Ordering}; /// Returns k-th smallest element of an array. /// Time complexity is stably O(nlog(k)) in all cases /// Extra space is required to maintain the heap, and it doesn't /// mutate the input list. /// /// It is preferrable to the partition-based algorithm in cases when /// we want to maintain the kth smallest element dynamically against /// a stream of elements. In that case, once the heap is built, further /// operation's complexity is O(log(k)). pub fn kth_smallest_heap<T>(input: &[T], k: usize) -> Option<T> where T: Ord + Copy, { if input.len() < k { return None; } // heap will maintain the kth smallest elements // seen so far, when new elements, E_new arrives, // it is compared with the largest element of the // current Heap E_large, which is the current kth // smallest elements. // if E_new > E_large, then E_new cannot be the kth // smallest because there are already k elements smaller // than it // otherwise, E_large cannot be the kth smallest, and should // be removed from the heap and E_new should be added let mut heap = Heap::new_max(); // first k elements goes to the heap as the baseline for &val in input.iter().take(k) { heap.add(val); } for &val in input.iter().skip(k) { // compare new value to the current kth smallest value let cur_big = heap.pop().unwrap(); // heap.pop() can't be None match val.cmp(&cur_big) { Ordering::Greater => { heap.add(cur_big); } _ => { heap.add(val); } } } heap.pop() } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { let zero: [u8; 0] = []; let first = kth_smallest_heap(&zero, 1); assert_eq!(None, first); } #[test] fn one_element() { let one = [1]; let first = kth_smallest_heap(&one, 1); assert_eq!(1, first.unwrap()); } #[test] fn many_elements() { // 0 1 3 4 5 7 8 9 9 10 12 13 16 17 let many = [9, 17, 3, 16, 13, 10, 1, 5, 7, 12, 4, 8, 9, 0]; let first = kth_smallest_heap(&many, 1); let third = kth_smallest_heap(&many, 3); let sixth = kth_smallest_heap(&many, 6); let fourteenth = kth_smallest_heap(&many, 14); assert_eq!(0, first.unwrap()); assert_eq!(3, third.unwrap()); assert_eq!(7, sixth.unwrap()); assert_eq!(17, fourteenth.unwrap()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/interpolation_search.rs
src/searching/interpolation_search.rs
pub fn interpolation_search<Ordering>(nums: &[i32], item: &i32) -> Result<usize, usize> { // early check if nums.is_empty() { return Err(0); } let mut low: usize = 0; let mut high: usize = nums.len() - 1; while low <= high { if *item < nums[low] || *item > nums[high] { break; } let offset: usize = low + (((high - low) / (nums[high] - nums[low]) as usize) * (*item - nums[low]) as usize); match nums[offset].cmp(item) { std::cmp::Ordering::Equal => return Ok(offset), std::cmp::Ordering::Less => low = offset + 1, std::cmp::Ordering::Greater => high = offset - 1, } } Err(0) } #[cfg(test)] mod tests { use super::*; use std::cmp::Ordering; #[test] fn returns_err_if_empty_slice() { let nums = []; assert_eq!(interpolation_search::<Ordering>(&nums, &3), Err(0)); } #[test] fn returns_err_if_target_not_found() { let nums = [1, 2, 3, 4, 5, 6]; assert_eq!(interpolation_search::<Ordering>(&nums, &10), Err(0)); } #[test] fn returns_first_index() { let index: Result<usize, usize> = interpolation_search::<Ordering>(&[1, 2, 3, 4, 5], &1); assert_eq!(index, Ok(0)); } #[test] fn returns_last_index() { let index: Result<usize, usize> = interpolation_search::<Ordering>(&[1, 2, 3, 4, 5], &5); assert_eq!(index, Ok(4)); } #[test] fn returns_middle_index() { let index: Result<usize, usize> = interpolation_search::<Ordering>(&[1, 2, 3, 4, 5], &3); assert_eq!(index, Ok(2)); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/kth_smallest.rs
src/searching/kth_smallest.rs
use crate::sorting::partition; use std::cmp::{Ordering, PartialOrd}; /// Returns k-th smallest element of an array, i.e. its order statistics. /// Time complexity is O(n^2) in the worst case, but only O(n) on average. /// It mutates the input, and therefore does not require additional space. pub fn kth_smallest<T>(input: &mut [T], k: usize) -> Option<T> where T: PartialOrd + Copy, { if input.is_empty() { return None; } let kth = _kth_smallest(input, k, 0, input.len() - 1); Some(kth) } fn _kth_smallest<T>(input: &mut [T], k: usize, lo: usize, hi: usize) -> T where T: PartialOrd + Copy, { if lo == hi { return input[lo]; } let pivot = partition(input, lo, hi); let i = pivot - lo + 1; match k.cmp(&i) { Ordering::Equal => input[pivot], Ordering::Less => _kth_smallest(input, k, lo, pivot - 1), Ordering::Greater => _kth_smallest(input, k - i, pivot + 1, hi), } } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { let mut zero: [u8; 0] = []; let first = kth_smallest(&mut zero, 1); assert_eq!(None, first); } #[test] fn one_element() { let mut one = [1]; let first = kth_smallest(&mut one, 1); assert_eq!(1, first.unwrap()); } #[test] fn many_elements() { // 0 1 3 4 5 7 8 9 9 10 12 13 16 17 let mut many = [9, 17, 3, 16, 13, 10, 1, 5, 7, 12, 4, 8, 9, 0]; let first = kth_smallest(&mut many, 1); let third = kth_smallest(&mut many, 3); let sixth = kth_smallest(&mut many, 6); let fourteenth = kth_smallest(&mut many, 14); assert_eq!(0, first.unwrap()); assert_eq!(3, third.unwrap()); assert_eq!(7, sixth.unwrap()); assert_eq!(17, fourteenth.unwrap()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/fibonacci_search.rs
src/searching/fibonacci_search.rs
use std::cmp::min; use std::cmp::Ordering; pub fn fibonacci_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> { let len = arr.len(); if len == 0 { return None; } let mut start = -1; let mut f0 = 0; let mut f1 = 1; let mut f2 = 1; while f2 < len { f0 = f1; f1 = f2; f2 = f0 + f1; } while f2 > 1 { let index = min((f0 as isize + start) as usize, len - 1); match item.cmp(&arr[index]) { Ordering::Less => { f2 = f0; f1 -= f0; f0 = f2 - f1; } Ordering::Equal => return Some(index), Ordering::Greater => { f2 = f1; f1 = f0; f0 = f2 - f1; start = index as isize; } } } if (f1 != 0) && (&arr[len - 1] == item) { return Some(len - 1); } None } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { let index = fibonacci_search(&"a", &[]); assert_eq!(index, None); } #[test] fn one_item() { let index = fibonacci_search(&"a", &["a"]); assert_eq!(index, Some(0)); } #[test] fn search_strings() { let index = fibonacci_search(&"a", &["a", "b", "c", "d", "google", "zoo"]); assert_eq!(index, Some(0)); } #[test] fn search_ints() { let index = fibonacci_search(&4, &[1, 2, 3, 4]); assert_eq!(index, Some(3)); let index = fibonacci_search(&3, &[1, 2, 3, 4]); assert_eq!(index, Some(2)); let index = fibonacci_search(&2, &[1, 2, 3, 4]); assert_eq!(index, Some(1)); let index = fibonacci_search(&1, &[1, 2, 3, 4]); assert_eq!(index, Some(0)); } #[test] fn not_found() { let index = fibonacci_search(&5, &[1, 2, 3, 4]); assert_eq!(index, None); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/ternary_search_min_max.rs
src/searching/ternary_search_min_max.rs
/// Ternary search algorithm for finding maximum of unimodal function pub fn ternary_search_max( f: fn(f32) -> f32, mut start: f32, mut end: f32, absolute_precision: f32, ) -> f32 { while (start - end).abs() >= absolute_precision { let mid1 = start + (end - start) / 3.0; let mid2 = end - (end - start) / 3.0; let r1 = f(mid1); let r2 = f(mid2); if r1 < r2 { start = mid1; } else if r1 > r2 { end = mid2; } else { start = mid1; end = mid2; } } f(start) } /// Ternary search algorithm for finding minimum of unimodal function pub fn ternary_search_min( f: fn(f32) -> f32, mut start: f32, mut end: f32, absolute_precision: f32, ) -> f32 { while (start - end).abs() >= absolute_precision { let mid1 = start + (end - start) / 3.0; let mid2 = end - (end - start) / 3.0; let r1 = f(mid1); let r2 = f(mid2); if r1 < r2 { end = mid2; } else if r1 > r2 { start = mid1; } else { start = mid1; end = mid2; } } f(start) } #[cfg(test)] mod tests { use super::*; #[test] fn finds_max_value() { let expected = 4.0; let f = |x: f32| -x * x - 2.0 * x + 3.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.0000001; let result = ternary_search_max(f, start, end, absolute_precision); assert_eq!(result, expected); } #[test] fn finds_min_value() { let expected = 2.0; let f = |x: f32| x * x - 2.0 * x + 3.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.0000001; let result = ternary_search_min(f, start, end, absolute_precision); assert_eq!(result, expected); } #[test] fn finds_max_value_2() { let expected = 7.25; let f = |x: f32| -x.powi(2) + 3.0 * x + 5.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.000001; let result = ternary_search_max(f, start, end, absolute_precision); assert_eq!(result, expected); } #[test] fn finds_min_value_2() { let expected = 2.75; let f = |x: f32| x.powi(2) + 3.0 * x + 5.0; let start: f32 = -10000000000.0; let end: f32 = 10000000000.0; let absolute_precision = 0.000001; let result = ternary_search_min(f, start, end, absolute_precision); assert_eq!(result, expected); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/searching/exponential_search.rs
src/searching/exponential_search.rs
use std::cmp::Ordering; pub fn exponential_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> { let len = arr.len(); if len == 0 { return None; } let mut upper = 1; while (upper < len) && (&arr[upper] <= item) { upper *= 2; } if upper > len { upper = len } // binary search let mut lower = upper / 2; while lower < upper { let mid = lower + (upper - lower) / 2; match item.cmp(&arr[mid]) { Ordering::Less => upper = mid, Ordering::Equal => return Some(mid), Ordering::Greater => lower = mid + 1, } } None } #[cfg(test)] mod tests { use super::*; #[test] fn empty() { let index = exponential_search(&"a", &[]); assert_eq!(index, None); } #[test] fn one_item() { let index = exponential_search(&"a", &["a"]); assert_eq!(index, Some(0)); } #[test] fn search_strings() { let index = exponential_search(&"a", &["a", "b", "c", "d", "google", "zoo"]); assert_eq!(index, Some(0)); } #[test] fn search_ints() { let index = exponential_search(&4, &[1, 2, 3, 4]); assert_eq!(index, Some(3)); let index = exponential_search(&3, &[1, 2, 3, 4]); assert_eq!(index, Some(2)); let index = exponential_search(&2, &[1, 2, 3, 4]); assert_eq!(index, Some(1)); let index = exponential_search(&1, &[1, 2, 3, 4]); assert_eq!(index, Some(0)); } #[test] fn not_found() { let index = exponential_search(&5, &[1, 2, 3, 4]); assert_eq!(index, None); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/order_of_magnitude_conversion.rs
src/conversions/order_of_magnitude_conversion.rs
//! Length Unit Conversion //! //! This module provides conversion between metric length units ranging from //! meters to yottametres (10^24 meters). //! //! Available units: Meter, Kilometer, Megametre, Gigametre, Terametre, //! Petametre, Exametre, Zettametre, Yottametre //! //! # References //! //! - [Meter - Wikipedia](https://en.wikipedia.org/wiki/Meter) //! - [Kilometer - Wikipedia](https://en.wikipedia.org/wiki/Kilometer) //! - [Orders of Magnitude (Length) - Wikipedia](https://en.wikipedia.org/wiki/Orders_of_magnitude_(length)) use std::fmt; use std::str::FromStr; /// Represents different metric length units. /// /// Each variant corresponds to a specific power of 10 relative to the base unit (meter). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MetricLengthUnit { /// Meter (m) - base unit, 10^0 meters Meter, /// Kilometer (km) - 10^3 meters Kilometer, /// Megametre (Mm) - 10^6 meters Megametre, /// Gigametre (Gm) - 10^9 meters Gigametre, /// Terametre (Tm) - 10^12 meters Terametre, /// Petametre (Pm) - 10^15 meters Petametre, /// Exametre (Em) - 10^18 meters Exametre, /// Zettametre (Zm) - 10^21 meters Zettametre, /// Yottametre (Ym) - 10^24 meters Yottametre, } impl MetricLengthUnit { /// Returns the exponent (power of 10) for this unit relative to meters. /// /// # Example /// /// ``` /// use the_algorithms_rust::conversions::MetricLengthUnit; /// /// assert_eq!(MetricLengthUnit::Meter.exponent(), 0); /// assert_eq!(MetricLengthUnit::Kilometer.exponent(), 3); /// assert_eq!(MetricLengthUnit::Megametre.exponent(), 6); /// ``` pub fn exponent(&self) -> i32 { match self { MetricLengthUnit::Meter => 0, MetricLengthUnit::Kilometer => 3, MetricLengthUnit::Megametre => 6, MetricLengthUnit::Gigametre => 9, MetricLengthUnit::Terametre => 12, MetricLengthUnit::Petametre => 15, MetricLengthUnit::Exametre => 18, MetricLengthUnit::Zettametre => 21, MetricLengthUnit::Yottametre => 24, } } /// Returns the standard abbreviation for this unit. /// /// # Example /// /// ``` /// use the_algorithms_rust::conversions::MetricLengthUnit; /// /// assert_eq!(MetricLengthUnit::Meter.symbol(), "m"); /// assert_eq!(MetricLengthUnit::Kilometer.symbol(), "km"); /// ``` pub fn symbol(&self) -> &'static str { match self { MetricLengthUnit::Meter => "m", MetricLengthUnit::Kilometer => "km", MetricLengthUnit::Megametre => "Mm", MetricLengthUnit::Gigametre => "Gm", MetricLengthUnit::Terametre => "Tm", MetricLengthUnit::Petametre => "Pm", MetricLengthUnit::Exametre => "Em", MetricLengthUnit::Zettametre => "Zm", MetricLengthUnit::Yottametre => "Ym", } } } impl FromStr for MetricLengthUnit { type Err = String; /// Parses a unit from a string (case-insensitive, handles plurals). /// /// Accepts both full names (e.g., "meter", "meters") and symbols (e.g., "m", "km"). /// /// # Example /// /// ``` /// use the_algorithms_rust::conversions::MetricLengthUnit; /// use std::str::FromStr; /// /// assert_eq!(MetricLengthUnit::from_str("meter").unwrap(), MetricLengthUnit::Meter); /// assert_eq!(MetricLengthUnit::from_str("km").unwrap(), MetricLengthUnit::Kilometer); /// assert_eq!(MetricLengthUnit::from_str("METERS").unwrap(), MetricLengthUnit::Meter); /// ``` fn from_str(s: &str) -> Result<Self, Self::Err> { // Sanitize: lowercase and remove trailing 's' let sanitized = s.to_lowercase().trim_end_matches('s').to_string(); match sanitized.as_str() { "meter" | "m" => Ok(MetricLengthUnit::Meter), "kilometer" | "km" => Ok(MetricLengthUnit::Kilometer), "megametre" | "megameter" | "mm" => Ok(MetricLengthUnit::Megametre), "gigametre" | "gigameter" | "gm" => Ok(MetricLengthUnit::Gigametre), "terametre" | "terameter" | "tm" => Ok(MetricLengthUnit::Terametre), "petametre" | "petameter" | "pm" => Ok(MetricLengthUnit::Petametre), "exametre" | "exameter" | "em" => Ok(MetricLengthUnit::Exametre), "zettametre" | "zettameter" | "zm" => Ok(MetricLengthUnit::Zettametre), "yottametre" | "yottameter" | "ym" => Ok(MetricLengthUnit::Yottametre), _ => Err(format!( "Invalid unit: '{s}'. Valid units are: m, km, Mm, Gm, Tm, Pm, Em, Zm, Ym" )), } } } impl fmt::Display for MetricLengthUnit { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.symbol()) } } /// Converts a length value from one unit to another. /// /// # Arguments /// /// * `value` - The numeric value to convert /// * `from` - The unit to convert from /// * `to` - The unit to convert to /// /// # Returns /// /// The converted value in the target unit /// /// # Example /// /// ``` /// use the_algorithms_rust::conversions::{MetricLengthUnit, convert_metric_length}; /// /// let result = convert_metric_length(1.0, MetricLengthUnit::Meter, MetricLengthUnit::Kilometer); /// assert_eq!(result, 0.001); /// /// let result = convert_metric_length(1.0, MetricLengthUnit::Kilometer, MetricLengthUnit::Meter); /// assert_eq!(result, 1000.0); /// ``` pub fn convert_metric_length(value: f64, from: MetricLengthUnit, to: MetricLengthUnit) -> f64 { let from_exp = from.exponent(); let to_exp = to.exponent(); let exponent = from_exp - to_exp; value * 10_f64.powi(exponent) } /// Converts a length value from one unit to another using string unit names. /// /// This function accepts both full unit names and abbreviations, and is case-insensitive. /// It also handles plural forms (e.g., "meters" and "meter" both work). /// /// # Arguments /// /// * `value` - The numeric value to convert /// * `from_type` - The unit to convert from (as a string) /// * `to_type` - The unit to convert to (as a string) /// /// # Returns /// /// `Ok(f64)` with the converted value, or `Err(String)` if either unit is invalid /// /// # Example /// /// ``` /// use the_algorithms_rust::conversions::metric_length_conversion; /// /// let result = metric_length_conversion(1.0, "meter", "kilometer").unwrap(); /// assert_eq!(result, 0.001); /// /// let result = metric_length_conversion(1.0, "km", "m").unwrap(); /// assert_eq!(result, 1000.0); /// /// // Case insensitive and handles plurals /// let result = metric_length_conversion(5.0, "METERS", "kilometers").unwrap(); /// assert_eq!(result, 0.005); /// /// // Invalid unit returns error /// assert!(metric_length_conversion(1.0, "wrongUnit", "meter").is_err()); /// ``` pub fn metric_length_conversion(value: f64, from_type: &str, to_type: &str) -> Result<f64, String> { let from_unit = MetricLengthUnit::from_str(from_type).map_err(|_| { format!( "Invalid 'from_type' value: '{from_type}'.\nConversion abbreviations are: m, km, Mm, Gm, Tm, Pm, Em, Zm, Ym" ) })?; let to_unit = MetricLengthUnit::from_str(to_type).map_err(|_| { format!( "Invalid 'to_type' value: '{to_type}'.\nConversion abbreviations are: m, km, Mm, Gm, Tm, Pm, Em, Zm, Ym" ) })?; Ok(convert_metric_length(value, from_unit, to_unit)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_unit_exponents() { assert_eq!(MetricLengthUnit::Meter.exponent(), 0); assert_eq!(MetricLengthUnit::Kilometer.exponent(), 3); assert_eq!(MetricLengthUnit::Megametre.exponent(), 6); assert_eq!(MetricLengthUnit::Gigametre.exponent(), 9); assert_eq!(MetricLengthUnit::Terametre.exponent(), 12); assert_eq!(MetricLengthUnit::Petametre.exponent(), 15); assert_eq!(MetricLengthUnit::Exametre.exponent(), 18); assert_eq!(MetricLengthUnit::Zettametre.exponent(), 21); assert_eq!(MetricLengthUnit::Yottametre.exponent(), 24); } #[test] fn test_unit_symbols() { assert_eq!(MetricLengthUnit::Meter.symbol(), "m"); assert_eq!(MetricLengthUnit::Kilometer.symbol(), "km"); assert_eq!(MetricLengthUnit::Megametre.symbol(), "Mm"); assert_eq!(MetricLengthUnit::Gigametre.symbol(), "Gm"); assert_eq!(MetricLengthUnit::Terametre.symbol(), "Tm"); assert_eq!(MetricLengthUnit::Petametre.symbol(), "Pm"); assert_eq!(MetricLengthUnit::Exametre.symbol(), "Em"); assert_eq!(MetricLengthUnit::Zettametre.symbol(), "Zm"); assert_eq!(MetricLengthUnit::Yottametre.symbol(), "Ym"); } #[test] fn test_from_str_full_names() { assert_eq!( MetricLengthUnit::from_str("meter").unwrap(), MetricLengthUnit::Meter ); assert_eq!( MetricLengthUnit::from_str("kilometer").unwrap(), MetricLengthUnit::Kilometer ); assert_eq!( MetricLengthUnit::from_str("megametre").unwrap(), MetricLengthUnit::Megametre ); } #[test] fn test_from_str_symbols() { assert_eq!( MetricLengthUnit::from_str("m").unwrap(), MetricLengthUnit::Meter ); assert_eq!( MetricLengthUnit::from_str("km").unwrap(), MetricLengthUnit::Kilometer ); assert_eq!( MetricLengthUnit::from_str("Mm").unwrap(), MetricLengthUnit::Megametre ); assert_eq!( MetricLengthUnit::from_str("Gm").unwrap(), MetricLengthUnit::Gigametre ); } #[test] fn test_from_str_case_insensitive() { assert_eq!( MetricLengthUnit::from_str("METER").unwrap(), MetricLengthUnit::Meter ); assert_eq!( MetricLengthUnit::from_str("KiLoMeTeR").unwrap(), MetricLengthUnit::Kilometer ); assert_eq!( MetricLengthUnit::from_str("KM").unwrap(), MetricLengthUnit::Kilometer ); } #[test] fn test_from_str_plurals() { assert_eq!( MetricLengthUnit::from_str("meters").unwrap(), MetricLengthUnit::Meter ); assert_eq!( MetricLengthUnit::from_str("kilometers").unwrap(), MetricLengthUnit::Kilometer ); } #[test] fn test_from_str_invalid() { assert!(MetricLengthUnit::from_str("wrongUnit").is_err()); assert!(MetricLengthUnit::from_str("inch").is_err()); assert!(MetricLengthUnit::from_str("").is_err()); } #[test] fn test_convert_length_meter_to_kilometer() { let result = convert_metric_length(1.0, MetricLengthUnit::Meter, MetricLengthUnit::Kilometer); assert_eq!(result, 0.001); } #[test] fn test_convert_length_meter_to_megametre() { let result = convert_metric_length(1.0, MetricLengthUnit::Meter, MetricLengthUnit::Megametre); assert_eq!(result, 1e-6); } #[test] fn test_convert_length_gigametre_to_meter() { let result = convert_metric_length(1.0, MetricLengthUnit::Gigametre, MetricLengthUnit::Meter); assert_eq!(result, 1_000_000_000.0); } #[test] fn test_convert_length_gigametre_to_terametre() { let result = convert_metric_length( 1.0, MetricLengthUnit::Gigametre, MetricLengthUnit::Terametre, ); assert_eq!(result, 0.001); } #[test] fn test_convert_length_petametre_to_terametre() { let result = convert_metric_length( 1.0, MetricLengthUnit::Petametre, MetricLengthUnit::Terametre, ); assert_eq!(result, 1000.0); } #[test] fn test_convert_length_petametre_to_exametre() { let result = convert_metric_length(1.0, MetricLengthUnit::Petametre, MetricLengthUnit::Exametre); assert_eq!(result, 0.001); } #[test] fn test_convert_length_terametre_to_zettametre() { let result = convert_metric_length( 1.0, MetricLengthUnit::Terametre, MetricLengthUnit::Zettametre, ); assert_eq!(result, 1e-9); } #[test] fn test_convert_length_yottametre_to_zettametre() { let result = convert_metric_length( 1.0, MetricLengthUnit::Yottametre, MetricLengthUnit::Zettametre, ); assert_eq!(result, 1000.0); } #[test] fn test_convert_length_same_unit() { let result = convert_metric_length( 42.0, MetricLengthUnit::Kilometer, MetricLengthUnit::Kilometer, ); assert_eq!(result, 42.0); } #[test] fn test_length_conversion_str_basic() { let result = metric_length_conversion(1.0, "meter", "kilometer").unwrap(); assert_eq!(result, 0.001); } #[test] fn test_length_conversion_str_symbols() { let result = metric_length_conversion(1.0, "m", "km").unwrap(); assert_eq!(result, 0.001); } #[test] fn test_length_conversion_str_case_insensitive() { let result = metric_length_conversion(1.0, "METER", "KILOMETER").unwrap(); assert_eq!(result, 0.001); } #[test] fn test_length_conversion_str_plurals() { let result = metric_length_conversion(5.0, "meters", "kilometers").unwrap(); assert_eq!(result, 0.005); } #[test] fn test_length_conversion_str_invalid_from() { let result = metric_length_conversion(1.0, "wrongUnit", "meter"); assert!(result.is_err()); assert!(result.unwrap_err().contains("Invalid 'from_type'")); } #[test] fn test_length_conversion_str_invalid_to() { let result = metric_length_conversion(1.0, "meter", "inch"); assert!(result.is_err()); assert!(result.unwrap_err().contains("Invalid 'to_type'")); } #[test] fn test_length_conversion_str_large_values() { let result = metric_length_conversion(1000.0, "km", "m").unwrap(); assert_eq!(result, 1_000_000.0); } #[test] fn test_length_conversion_str_small_values() { let result = metric_length_conversion(0.001, "m", "km").unwrap(); assert_eq!(result, 0.000001); } #[test] fn test_all_conversions_reversible() { let units = [ MetricLengthUnit::Meter, MetricLengthUnit::Kilometer, MetricLengthUnit::Megametre, MetricLengthUnit::Gigametre, MetricLengthUnit::Terametre, ]; for &from in &units { for &to in &units { let forward = convert_metric_length(100.0, from, to); let backward = convert_metric_length(forward, to, from); assert!((backward - 100.0).abs() < 1e-9, "Conversion not reversible"); } } } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/decimal_to_octal.rs
src/conversions/decimal_to_octal.rs
// Author: NithinU2802 // Decimal to Octal Converter: Converts Decimal to Octal // Wikipedia References: // 1. https://en.wikipedia.org/wiki/Decimal // 2. https://en.wikipedia.org/wiki/Octal pub fn decimal_to_octal(decimal_num: u64) -> String { if decimal_num == 0 { return "0".to_string(); } let mut num = decimal_num; let mut octal = String::new(); while num > 0 { let remainder = num % 8; octal.push_str(&remainder.to_string()); num /= 8; } // Reverse the string to get the correct octal representation octal.chars().rev().collect() } #[cfg(test)] mod tests { use super::*; #[test] fn test_decimal_to_octal() { assert_eq!(decimal_to_octal(8), "10"); assert_eq!(decimal_to_octal(15), "17"); assert_eq!(decimal_to_octal(255), "377"); assert_eq!(decimal_to_octal(100), "144"); assert_eq!(decimal_to_octal(0), "0"); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/octal_to_hexadecimal.rs
src/conversions/octal_to_hexadecimal.rs
// Author: NithinU2802 // Octal to Hexadecimal Converter: Converts Octal to Hexadecimal // Wikipedia References: // 1. https://en.wikipedia.org/wiki/Octal // 2. https://en.wikipedia.org/wiki/Hexadecimal pub fn octal_to_hexadecimal(octal_str: &str) -> Result<String, &'static str> { let octal_str = octal_str.trim(); if octal_str.is_empty() { return Err("Empty string"); } // Validate octal string if !octal_str.chars().all(|c| ('0'..='7').contains(&c)) { return Err("Invalid octal string"); } // Convert octal to decimal first let decimal = u64::from_str_radix(octal_str, 8).map_err(|_| "Conversion error")?; // Special case for zero if decimal == 0 { return Ok("0".to_string()); } // Convert decimal to hexadecimal Ok(format!("{decimal:X}")) } #[cfg(test)] mod tests { use super::*; #[test] fn test_octal_to_hexadecimal() { assert_eq!(octal_to_hexadecimal("12"), Ok("A".to_string())); assert_eq!(octal_to_hexadecimal("377"), Ok("FF".to_string())); assert_eq!(octal_to_hexadecimal("144"), Ok("64".to_string())); assert_eq!(octal_to_hexadecimal("0"), Ok("0".to_string())); } #[test] fn test_invalid_input() { assert_eq!(octal_to_hexadecimal(""), Err("Empty string")); assert_eq!(octal_to_hexadecimal("8"), Err("Invalid octal string")); assert_eq!(octal_to_hexadecimal("9"), Err("Invalid octal string")); assert_eq!(octal_to_hexadecimal("ABC"), Err("Invalid octal string")); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/binary_to_hexadecimal.rs
src/conversions/binary_to_hexadecimal.rs
// Author : cyrixninja // Binary to Hex Converter : Converts Binary to Hexadecimal // Wikipedia References : 1. https://en.wikipedia.org/wiki/Hexadecimal // 2. https://en.wikipedia.org/wiki/Binary_number static BITS_TO_HEX: &[(u8, &str)] = &[ (0b0000, "0"), (0b0001, "1"), (0b0010, "2"), (0b0011, "3"), (0b0100, "4"), (0b0101, "5"), (0b0110, "6"), (0b0111, "7"), (0b1000, "8"), (0b1001, "9"), (0b1010, "a"), (0b1011, "b"), (0b1100, "c"), (0b1101, "d"), (0b1110, "e"), (0b1111, "f"), ]; pub fn binary_to_hexadecimal(binary_str: &str) -> String { let binary_str = binary_str.trim(); if binary_str.is_empty() { return String::from("Invalid Input"); } let is_negative = binary_str.starts_with('-'); let binary_str = if is_negative { &binary_str[1..] } else { binary_str }; if !binary_str.chars().all(|c| c == '0' || c == '1') { return String::from("Invalid Input"); } let padded_len = (4 - (binary_str.len() % 4)) % 4; let binary_str = format!( "{:0width$}", binary_str, width = binary_str.len() + padded_len ); // Convert binary to hexadecimal let mut hexadecimal = String::with_capacity(binary_str.len() / 4 + 2); hexadecimal.push_str("0x"); for chunk in binary_str.as_bytes().chunks(4) { let mut nibble = 0; for (i, &byte) in chunk.iter().enumerate() { nibble |= (byte - b'0') << (3 - i); } let hex_char = BITS_TO_HEX .iter() .find(|&&(bits, _)| bits == nibble) .map(|&(_, hex)| hex) .unwrap(); hexadecimal.push_str(hex_char); } if is_negative { format!("-{hexadecimal}") } else { hexadecimal } } #[cfg(test)] mod tests { use super::*; #[test] fn test_empty_string() { let input = ""; let expected = "Invalid Input"; assert_eq!(binary_to_hexadecimal(input), expected); } #[test] fn test_invalid_binary() { let input = "a"; let expected = "Invalid Input"; assert_eq!(binary_to_hexadecimal(input), expected); } #[test] fn test_binary() { let input = "00110110"; let expected = "0x36"; assert_eq!(binary_to_hexadecimal(input), expected); } #[test] fn test_padded_binary() { let input = " 1010 "; let expected = "0xa"; assert_eq!(binary_to_hexadecimal(input), expected); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false
TheAlgorithms/Rust
https://github.com/TheAlgorithms/Rust/blob/38024b01c29eb05f733d480f88f19f0c06922a85/src/conversions/binary_to_decimal.rs
src/conversions/binary_to_decimal.rs
use num_traits::CheckedAdd; pub fn binary_to_decimal(binary: &str) -> Option<u128> { if binary.len() > 128 { return None; } let mut num = 0; let mut idx_val = 1; for bit in binary.chars().rev() { match bit { '1' => { if let Some(sum) = num.checked_add(&idx_val) { num = sum; } else { return None; } } '0' => {} _ => return None, } idx_val <<= 1; } Some(num) } #[cfg(test)] mod tests { use super::binary_to_decimal; #[test] fn basic_binary_to_decimal() { assert_eq!(binary_to_decimal("0000000110"), Some(6)); assert_eq!(binary_to_decimal("1000011110"), Some(542)); assert_eq!(binary_to_decimal("1111111111"), Some(1023)); } #[test] fn big_binary_to_decimal() { assert_eq!( binary_to_decimal("111111111111111111111111"), Some(16_777_215) ); // 32 bits assert_eq!( binary_to_decimal("11111111111111111111111111111111"), Some(4_294_967_295) ); // 64 bits assert_eq!( binary_to_decimal("1111111111111111111111111111111111111111111111111111111111111111"), Some(18_446_744_073_709_551_615u128) ); } #[test] fn very_big_binary_to_decimal() { // 96 bits assert_eq!( binary_to_decimal( "1111111111111111111111111111111111111111111111111111111111111111\ 11111111111111111111111111111111" ), Some(79_228_162_514_264_337_593_543_950_335u128) ); // 128 bits assert_eq!( binary_to_decimal( "1111111111111111111111111111111111111111111111111111111111111111\ 1111111111111111111111111111111111111111111111111111111111111111" ), Some(340_282_366_920_938_463_463_374_607_431_768_211_455u128) ); // 129 bits, should overflow assert!(binary_to_decimal( "1111111111111111111111111111111111111111111111111111111111111111\ 11111111111111111111111111111111111111111111111111111111111111111" ) .is_none()); // obviously none assert!(binary_to_decimal( "1111111111111111111111111111111111111111111111111111111111111111\ 1111111111111111111111111111111111111111111111111111111111111\ 1111111111111111111111111111111111111111111111111111111111111\ 1111111111111111111111111111111111111111111111111111111111111\ 1111111111111111111111111111111111111111111111111111111111111\ 1111111111111111111111111111111111111111111111111111111111111\ 1111111111111111111111111111111111111111111111111111111111111" ) .is_none()); } }
rust
MIT
38024b01c29eb05f733d480f88f19f0c06922a85
2026-01-04T15:37:39.002409Z
false