Created
November 12, 2024 08:40
-
-
Save Aviksaikat/8e63d58570f8284b11649adb5a5d50a1 to your computer and use it in GitHub Desktop.
Find square root of U256 or any integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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