Skip to content

Commit 7bde3ab

Browse files
committed
Add log2
1 parent 1abfc77 commit 7bde3ab

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

std/src/lib.rs

+23
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,29 @@ pub mod error;
4545
#[doc(hidden)]
4646
pub use std::*;
4747

48+
/// Returns the base-2 logarithm of `x`.
49+
///
50+
/// ```
51+
/// use ark_std::log2;
52+
///
53+
/// assert_eq!(log2(16), 4);
54+
/// assert_eq!(log2(17), 5);
55+
/// assert_eq!(log2(1), 0);
56+
/// assert_eq!(log2(0), 0);
57+
/// assert_eq!(log2(usize::MAX), (core::mem::size_of::<usize>() * 8) as u32);
58+
/// assert_eq!(log2(1 << 15), 15);
59+
/// assert_eq!(log2(2usize.pow(18)), 18);
60+
/// ```
61+
pub fn log2(x: usize) -> u32 {
62+
if x == 0 {
63+
0
64+
} else if x.is_power_of_two() {
65+
1usize.leading_zeros() - x.leading_zeros()
66+
} else {
67+
0usize.leading_zeros() - x.leading_zeros()
68+
}
69+
}
70+
4871
/// Creates parallel iterator over refs if `parallel` feature is enabled.
4972
#[macro_export]
5073
macro_rules! cfg_iter {

0 commit comments

Comments
 (0)