diff --git a/src/euler53/Cargo.toml b/src/euler53/Cargo.toml new file mode 100644 index 0000000..2e8bbf4 --- /dev/null +++ b/src/euler53/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "euler53" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rust-gmp = "*" diff --git a/src/euler53/src/main.rs b/src/euler53/src/main.rs new file mode 100644 index 0000000..4b17d57 --- /dev/null +++ b/src/euler53/src/main.rs @@ -0,0 +1,84 @@ +extern crate gmp; + +use gmp::mpz::Mpz as Int; + +static mut ZERO: Option = None; +static mut ONE: Option = None; +static mut THRESHOLD: Option = None; + +fn main() { + init_statics(); + + let mut accum = 0; + for n in 1..=100 { + for r in 1..=n { + let mut nn = Int::new(); + nn.set_from_str_radix(n.to_string().as_str(), 10); + + let mut rr = Int::new(); + rr.set_from_str_radix(r.to_string().as_str(), 10); + + unsafe { + if combinations(rr, nn) > THRESHOLD.clone().unwrap_unchecked() { + accum += 1; + } + } + } + } + println!("{accum}"); +} + +unsafe fn combinations(r: Int, n: Int) -> Int { + faculty(n.clone()) / (faculty(r.clone()) * faculty(n - r)) +} + +fn init_statics() { + let mut zero = Int::new(); + zero.set_from_str_radix("0", 10); + unsafe { + ZERO = Some(zero); + } + + let mut one = Int::new(); + one.set_from_str_radix("1", 10); + unsafe { + ONE = Some(one); + } + + let mut threshold = Int::new(); + threshold.set_from_str_radix("1 000 000", 10); + unsafe { + THRESHOLD = Some(threshold); + } +} + +unsafe fn faculty(x: Int) -> Int { + if x == ZERO.clone().unwrap_unchecked() { + ONE.clone().unwrap_unchecked() + } else { + x.clone() * faculty(x - 1) + } +} + +#[cfg(test)] +mod test { + use super::Int; + use crate::combinations; + use crate::init_statics; + + #[test] + fn test_10_23() { + init_statics(); + + let mut r = Int::new(); + r.set_from_str_radix("10", 10); + + let mut n = Int::new(); + n.set_from_str_radix("23", 10); + + let mut result = Int::new(); + result.set_from_str_radix("1144066", 10); + + assert_eq!(unsafe { combinations(r, n) }, result); + } +}