Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
* [Counting Bits](https://github.com/TheAlgorithms/Rust/blob/master/src/bit_manipulation/counting_bits.rs)
* [Highest Set Bit](https://github.com/TheAlgorithms/Rust/blob/master/src/bit_manipulation/highest_set_bit.rs)
* [N Bits Gray Code](https://github.com/TheAlgorithms/Rust/blob/master/src/bit_manipulation/n_bits_gray_code.rs)
* [Previous Power of Two](https://github.com/TheAlgorithms/Rust/blob/master/src/bit_manipulation/find_previous_power_of_two.rs)
* [Reverse Bits](https://github.com/TheAlgorithms/Rust/blob/master/src/bit_manipulation/reverse_bits.rs)
* [Sum of Two Integers](https://github.com/TheAlgorithms/Rust/blob/master/src/bit_manipulation/sum_of_two_integers.rs)
* [Swap Odd and Even Bits](https://github.com/TheAlgorithms/Rust/blob/master/src/bit_manipulation/swap_odd_even_bits.rs)
Expand Down Expand Up @@ -195,7 +196,7 @@
* [Gradient Descent](https://github.com/TheAlgorithms/Rust/blob/master/src/machine_learning/optimization/gradient_descent.rs)
* [Momentum](https://github.com/TheAlgorithms/Rust/blob/master/src/machine_learning/optimization/momentum.rs)
* Math
* [Abs](https://github.com/TheAlgorithms/Rust/blob/master/src/math/abs.rs)
* [Absolute](https://github.com/TheAlgorithms/Rust/blob/master/src/math/abs.rs)
* [Aliquot Sum](https://github.com/TheAlgorithms/Rust/blob/master/src/math/aliquot_sum.rs)
* [Amicable Numbers](https://github.com/TheAlgorithms/Rust/blob/master/src/math/amicable_numbers.rs)
* [Area Of Polygon](https://github.com/TheAlgorithms/Rust/blob/master/src/math/area_of_polygon.rs)
Expand Down Expand Up @@ -259,18 +260,18 @@
* [Prime Numbers](https://github.com/TheAlgorithms/Rust/blob/master/src/math/prime_numbers.rs)
* [Quadratic Residue](https://github.com/TheAlgorithms/Rust/blob/master/src/math/quadratic_residue.rs)
* [Random](https://github.com/TheAlgorithms/Rust/blob/master/src/math/random.rs)
* [Relu](https://github.com/TheAlgorithms/Rust/blob/master/src/math/relu.rs)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sieve_of_eratosthenes.rs)
* [ReLU](https://github.com/TheAlgorithms/Rust/blob/master/src/math/relu.rs)
* [Sieve of Eratosthenes](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sieve_of_eratosthenes.rs)
* [Sigmoid](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sigmoid.rs)
* [Signum](https://github.com/TheAlgorithms/Rust/blob/master/src/math/signum.rs)
* [Simpsons Integration](https://github.com/TheAlgorithms/Rust/blob/master/src/math/simpsons_integration.rs)
* [Softmax](https://github.com/TheAlgorithms/Rust/blob/master/src/math/softmax.rs)
* [Sprague Grundy Theorem](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sprague_grundy_theorem.rs)
* [Square Pyramidal Numbers](https://github.com/TheAlgorithms/Rust/blob/master/src/math/square_pyramidal_numbers.rs)
* [Square Root](https://github.com/TheAlgorithms/Rust/blob/master/src/math/square_root.rs)
* [Sum Of Digits](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sum_of_digits.rs)
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sum_of_geometric_progression.rs)
* [Sum Of Harmonic Series](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sum_of_harmonic_series.rs)
* [Sum of Digits](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sum_of_digits.rs)
* [Sum of Geometric Progression](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sum_of_geometric_progression.rs)
* [Sum of Harmonic Series](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sum_of_harmonic_series.rs)
* [Sylvester Sequence](https://github.com/TheAlgorithms/Rust/blob/master/src/math/sylvester_sequence.rs)
* [Tanh](https://github.com/TheAlgorithms/Rust/blob/master/src/math/tanh.rs)
* [Trapezoidal Integration](https://github.com/TheAlgorithms/Rust/blob/master/src/math/trapezoidal_integration.rs)
Expand All @@ -285,16 +286,16 @@
* Number Theory
* [Compute Totient](https://github.com/TheAlgorithms/Rust/blob/master/src/number_theory/compute_totient.rs)
* [Euler Totient](https://github.com/TheAlgorithms/Rust/blob/master/src/number_theory/euler_totient.rs)
* [Kth Factor](https://github.com/TheAlgorithms/Rust/blob/master/src/number_theory/kth_factor.rs)
* [K-th Factor](https://github.com/TheAlgorithms/Rust/blob/master/src/number_theory/kth_factor.rs)
* Searching
* [Binary Search](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/binary_search.rs)
* [Binary Search Recursive](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/binary_search_recursive.rs)
* [Exponential Search](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/exponential_search.rs)
* [Fibonacci Search](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/fibonacci_search.rs)
* [Interpolation Search](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/interpolation_search.rs)
* [Jump Search](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/jump_search.rs)
* [Kth Smallest](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/kth_smallest.rs)
* [Kth Smallest Heap](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/kth_smallest_heap.rs)
* [K-th Smallest](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/kth_smallest.rs)
* [K-th Smallest Heap](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/kth_smallest_heap.rs)
* [Linear Search](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/linear_search.rs)
* [Moore Voting](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/moore_voting.rs)
* [Quick Select](https://github.com/TheAlgorithms/Rust/blob/master/src/searching/quick_select.rs)
Expand Down
172 changes: 172 additions & 0 deletions src/bit_manipulation/find_previous_power_of_two.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
//! Previous Power of Two
//!
//! This module provides a function to find the largest power of two that is less than
//! or equal to a given non-negative integer.
//!
//! # Algorithm
//!
//! The algorithm works by repeatedly left-shifting (doubling) a power value starting
//! from 1 until it exceeds the input number, then returning the previous power (by
//! right-shifting once).
//!
//! For more information: <https://stackoverflow.com/questions/1322510>

/// Finds the largest power of two that is less than or equal to a given integer.
///
/// The function uses bit shifting to efficiently find the power of two. It starts
/// with 1 and keeps doubling (left shift) until it exceeds the input, then returns
/// the previous value (right shift).
///
/// # Arguments
///
/// * `number` - A non-negative integer
///
/// # Returns
///
/// A `Result` containing:
/// - `Ok(u32)` - The largest power of two ≤ the input number
/// - `Err(String)` - An error message if the input is negative
///
/// # Examples
///
/// ```
/// use the_algorithms_rust::bit_manipulation::find_previous_power_of_two;
///
/// assert_eq!(find_previous_power_of_two(0).unwrap(), 0);
/// assert_eq!(find_previous_power_of_two(1).unwrap(), 1);
/// assert_eq!(find_previous_power_of_two(2).unwrap(), 2);
/// assert_eq!(find_previous_power_of_two(3).unwrap(), 2);
/// assert_eq!(find_previous_power_of_two(4).unwrap(), 4);
/// assert_eq!(find_previous_power_of_two(5).unwrap(), 4);
/// assert_eq!(find_previous_power_of_two(8).unwrap(), 8);
/// assert_eq!(find_previous_power_of_two(15).unwrap(), 8);
/// assert_eq!(find_previous_power_of_two(16).unwrap(), 16);
/// assert_eq!(find_previous_power_of_two(17).unwrap(), 16);
///
/// // Negative numbers return an error
/// assert!(find_previous_power_of_two(-5).is_err());
/// ```
///
/// # Errors
///
/// Returns an error if the input number is negative.
pub fn find_previous_power_of_two(number: i32) -> Result<u32, String> {
if number < 0 {
return Err("Input must be a non-negative integer".to_string());
}

let number = number as u32;

if number == 0 {
return Ok(0);
}

let mut power = 1u32;
while power <= number {
power <<= 1; // Equivalent to multiplying by 2
}

Ok(if number > 1 { power >> 1 } else { 1 })
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_zero() {
assert_eq!(find_previous_power_of_two(0).unwrap(), 0);
}

#[test]
fn test_one() {
assert_eq!(find_previous_power_of_two(1).unwrap(), 1);
}

#[test]
fn test_powers_of_two() {
assert_eq!(find_previous_power_of_two(2).unwrap(), 2);
assert_eq!(find_previous_power_of_two(4).unwrap(), 4);
assert_eq!(find_previous_power_of_two(8).unwrap(), 8);
assert_eq!(find_previous_power_of_two(16).unwrap(), 16);
assert_eq!(find_previous_power_of_two(32).unwrap(), 32);
assert_eq!(find_previous_power_of_two(64).unwrap(), 64);
assert_eq!(find_previous_power_of_two(128).unwrap(), 128);
assert_eq!(find_previous_power_of_two(256).unwrap(), 256);
assert_eq!(find_previous_power_of_two(512).unwrap(), 512);
assert_eq!(find_previous_power_of_two(1024).unwrap(), 1024);
}

#[test]
fn test_numbers_between_powers() {
// Between 2 and 4
assert_eq!(find_previous_power_of_two(3).unwrap(), 2);

// Between 4 and 8
assert_eq!(find_previous_power_of_two(5).unwrap(), 4);
assert_eq!(find_previous_power_of_two(6).unwrap(), 4);
assert_eq!(find_previous_power_of_two(7).unwrap(), 4);

// Between 8 and 16
assert_eq!(find_previous_power_of_two(9).unwrap(), 8);
assert_eq!(find_previous_power_of_two(10).unwrap(), 8);
assert_eq!(find_previous_power_of_two(11).unwrap(), 8);
assert_eq!(find_previous_power_of_two(12).unwrap(), 8);
assert_eq!(find_previous_power_of_two(13).unwrap(), 8);
assert_eq!(find_previous_power_of_two(14).unwrap(), 8);
assert_eq!(find_previous_power_of_two(15).unwrap(), 8);

// Between 16 and 32
assert_eq!(find_previous_power_of_two(17).unwrap(), 16);
assert_eq!(find_previous_power_of_two(20).unwrap(), 16);
assert_eq!(find_previous_power_of_two(31).unwrap(), 16);
}

#[test]
fn test_range_0_to_17() {
// Test the exact output from the Python docstring
let expected = vec![0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16, 16];
let results: Vec<u32> = (0..18)
.map(|i| find_previous_power_of_two(i).unwrap())
.collect();
assert_eq!(results, expected);
}

#[test]
fn test_large_numbers() {
assert_eq!(find_previous_power_of_two(100).unwrap(), 64);
assert_eq!(find_previous_power_of_two(500).unwrap(), 256);
assert_eq!(find_previous_power_of_two(1000).unwrap(), 512);
assert_eq!(find_previous_power_of_two(2000).unwrap(), 1024);
assert_eq!(find_previous_power_of_two(10000).unwrap(), 8192);
}

#[test]
fn test_max_safe_values() {
assert_eq!(find_previous_power_of_two(1023).unwrap(), 512);
assert_eq!(find_previous_power_of_two(2047).unwrap(), 1024);
assert_eq!(find_previous_power_of_two(4095).unwrap(), 2048);
}

#[test]
fn test_negative_number_returns_error() {
let result = find_previous_power_of_two(-1);
assert!(result.is_err());
assert_eq!(result.unwrap_err(), "Input must be a non-negative integer");
}

#[test]
fn test_negative_numbers_return_errors() {
assert!(find_previous_power_of_two(-5).is_err());
assert!(find_previous_power_of_two(-10).is_err());
assert!(find_previous_power_of_two(-100).is_err());
}

#[test]
fn test_edge_cases() {
// One less than powers of two
assert_eq!(find_previous_power_of_two(127).unwrap(), 64);
assert_eq!(find_previous_power_of_two(255).unwrap(), 128);
assert_eq!(find_previous_power_of_two(511).unwrap(), 256);
}
}
2 changes: 2 additions & 0 deletions src/bit_manipulation/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod binary_coded_decimal;
mod counting_bits;
mod find_previous_power_of_two;
mod highest_set_bit;
mod n_bits_gray_code;
mod reverse_bits;
Expand All @@ -9,6 +10,7 @@ mod twos_complement;

pub use self::binary_coded_decimal::binary_coded_decimal;
pub use self::counting_bits::count_set_bits;
pub use self::find_previous_power_of_two::find_previous_power_of_two;
pub use self::highest_set_bit::find_highest_set_bit;
pub use self::n_bits_gray_code::generate_gray_code;
pub use self::reverse_bits::reverse_bits;
Expand Down