/// It is not actually necissary or even recommended to use this code. /// The compiler should always optimize division with constant denominators for you. /// This code is just to help understand how the compilers optimization works. #[inline(always)] pub fn div10(num: u32) -> (u32, u32) { // Calculate num / 10 // Note: 0.10 = 3435973837 / (1<<35) let quot: u32 = ((3435973837_u64 * num as u64) >> 35) as u32; // Calculate quot * 10 // Note: 10x = 2x + 4(2x) let quot2 = quot << 1; let quot8 = quot2 << 2; let quot10 = quot2 + quot8; // Calculate the remainder // Note: rem = num - (quotient * denominator) let rem = num - quot10; return (quot, rem); } #[cfg(test)] mod tests { use super::*; #[test] fn brute_check() { for i in 0..=u32::MAX { let ans = (i / 10, i % 10); assert_eq!(ans, div10(i)); } } }