From 8ff474860849b4fbb462b77346283260232ee097 Mon Sep 17 00:00:00 2001 From: Lucas Schumacher Date: Tue, 14 Jan 2025 13:38:20 -0500 Subject: [PATCH] first commit --- .gitignore | 1 + Cargo.toml | 9 +++++++++ src/lib.rs | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f2de597 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "fastdiv10" +version = "0.1.0" +edition = "2021" + +[dependencies] + +[dev-dependencies] +rayon = "1.10.0" diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..787817b --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,35 @@ +/// 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. +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 << 3; + 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::*; + use rayon::prelude::*; + + #[test] + /// This will take a REALLY long time + fn brute_check() { + (0..=u32::MAX).into_par_iter().for_each(|i| { + let ans = (i / 10, i % 10); + assert_eq!(ans, div10(i)); + }); + } +}