@@ -898,6 +898,45 @@ macro_rules! int_impl {
898898 acc. checked_mul( base)
899899 }
900900
901+ /// Returns the square root of the number, rounded down.
902+ ///
903+ /// Returns `None` if `self` is negative.
904+ ///
905+ /// # Examples
906+ ///
907+ /// Basic usage:
908+ /// ```
909+ #[ doc = concat!( "assert_eq!(10" , stringify!( $SelfT) , ".checked_isqrt(), Some(3));" ) ]
910+ /// ```
911+ #[ stable( feature = "isqrt" , since = "1.73.0" ) ]
912+ #[ rustc_const_stable( feature = "isqrt" , since = "1.73.0" ) ]
913+ #[ must_use = "this returns the result of the operation, \
914+ without modifying the original"]
915+ #[ inline]
916+ pub const fn checked_isqrt( self ) -> Option <Self > {
917+ if self < 0 {
918+ return None ;
919+ } else if self < 2 {
920+ return Some ( self ) ;
921+ }
922+
923+ let mut x: Self = self ;
924+ let mut c: Self = 0 ;
925+ let mut d: Self = 1 << ( self . ilog2( ) & !1 ) ;
926+
927+ while ( d != 0 ) {
928+ if x >= c + d {
929+ x -= c + d;
930+ c = ( c >> 1 ) + d;
931+ } else {
932+ c >>= 1 ;
933+ }
934+ d >>= 2 ;
935+ }
936+
937+ return Some ( c) ;
938+ }
939+
901940 /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
902941 /// bounds instead of overflowing.
903942 ///
@@ -2061,6 +2100,47 @@ macro_rules! int_impl {
20612100 acc * base
20622101 }
20632102
2103+ /// Returns the square root of the number, rounded down.
2104+ ///
2105+ /// # Panics
2106+ ///
2107+ /// This function will panic if `self` is negative.
2108+ ///
2109+ /// # Examples
2110+ ///
2111+ /// Basic usage:
2112+ /// ```
2113+ #[ doc = concat!( "assert_eq!(10" , stringify!( $SelfT) , ".isqrt(), 3);" ) ]
2114+ /// ```
2115+ #[ stable( feature = "isqrt" , since = "1.73.0" ) ]
2116+ #[ rustc_const_stable( feature = "isqrt" , since = "1.73.0" ) ]
2117+ #[ must_use = "this returns the result of the operation, \
2118+ without modifying the original"]
2119+ #[ inline]
2120+ pub const fn isqrt( self ) -> Self {
2121+ if self < 0 {
2122+ panic!( "argument of integer square root must be non-negative" )
2123+ } else if self < 2 {
2124+ return self ;
2125+ }
2126+
2127+ let mut x: Self = self ;
2128+ let mut c: Self = 0 ;
2129+ let mut d: Self = 1 << ( self . ilog2( ) & !1 ) ;
2130+
2131+ while ( d != 0 ) {
2132+ if x >= c + d {
2133+ x -= c + d;
2134+ c = ( c >> 1 ) + d;
2135+ } else {
2136+ c >>= 1 ;
2137+ }
2138+ d >>= 2 ;
2139+ }
2140+
2141+ return c;
2142+ }
2143+
20642144 /// Calculates the quotient of Euclidean division of `self` by `rhs`.
20652145 ///
20662146 /// This computes the integer `q` such that `self = q * rhs + r`, with
0 commit comments