Skip to content

Instantly share code, notes, and snippets.

@Aviksaikat
Created November 12, 2024 08:40
Show Gist options
  • Save Aviksaikat/8e63d58570f8284b11649adb5a5d50a1 to your computer and use it in GitHub Desktop.
Save Aviksaikat/8e63d58570f8284b11649adb5a5d50a1 to your computer and use it in GitHub Desktop.
Find square root of U256 or any integers
use alloy::primitives::U256;
fn integer_sqrt(n: U256) -> U256 {
// https://en.wikipedia.org/wiki/Integer_square_root
if n < U256::from(2) {
return n;
}
let small_candidate = integer_sqrt(n >> 2) << 1;
let large_candidate = small_candidate + U256::from(1);
if large_candidate * large_candidate > n {
small_candidate
} else {
large_candidate
}
}
fn main() {
let res = U256::from(64);
println!("{}", integer_sqrt(res));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment