macro_rules! impl_gcd_old_for_isize {
($T:ty) => { impl GcdOld for $T { /// Calculates the Greatest Common Divisor (GCD) of the number and /// `other`. The result is always positive. #[inline] fn gcd_old(&self, other: &Self) -> Self { // Use Stein's algorithm letmut m = *self; letmut n = *other; if m == 0 || n == 0 { return (m | n).abs();
}
// find common factors of 2 let shift = (m | n).trailing_zeros();
// The algorithm needs positive numbers, but the minimum value // can't be represented as a positive one. // It's also a power of two, so the gcd can be // calculated by bitshifting in that case
// Assuming two's complement, the number created by the shift // is positive for all numbers except gcd = abs(min value) // The call to .abs() causes a panic in debug mode if m == Self::min_value() || n == Self::min_value() { return (1 << shift).abs();
}
// guaranteed to be positive now, rest like unsigned algorithm
m = m.abs();
n = n.abs();
// divide n and m by 2 until odd // m inside loop
n >>= n.trailing_zeros();
while m != 0 {
m >>= m.trailing_zeros(); if n > m {
std::mem::swap(&mut n, &mut m)
}
m -= n;
}
macro_rules! impl_gcd_old_for_usize {
($T:ty) => { impl GcdOld for $T { /// Calculates the Greatest Common Divisor (GCD) of the number and /// `other`. The result is always positive. #[inline] fn gcd_old(&self, other: &Self) -> Self { // Use Stein's algorithm letmut m = *self; letmut n = *other; if m == 0 || n == 0 { return m | n;
}
// find common factors of 2 let shift = (m | n).trailing_zeros();
// divide n and m by 2 until odd // m inside loop
n >>= n.trailing_zeros();
while m != 0 {
m >>= m.trailing_zeros(); if n > m {
std::mem::swap(&mut n, &mut m)
}
m -= n;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.