first commit
This commit is contained in:
commit
8ff4748608
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
9
Cargo.toml
Normal file
9
Cargo.toml
Normal 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
35
src/lib.rs
Normal 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));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user