first commit

This commit is contained in:
Lucas Schumacher 2025-01-14 13:38:20 -05:00
commit 8ff4748608
3 changed files with 45 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

9
Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "fastdiv10"
version = "0.1.0"
edition = "2021"
[dependencies]
[dev-dependencies]
rayon = "1.10.0"

35
src/lib.rs Normal file
View File

@ -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));
});
}
}