This commit is contained in:
Dr. Matthias Ratajczak
2022-08-18 20:11:56 +02:00
parent b5c15fe1bb
commit 37f9c77f38
2 changed files with 93 additions and 0 deletions
+9
View File
@@ -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 = "*"
+84
View File
@@ -0,0 +1,84 @@
extern crate gmp;
use gmp::mpz::Mpz as Int;
static mut ZERO: Option<Int> = None;
static mut ONE: Option<Int> = None;
static mut THRESHOLD: Option<Int> = 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);
}
}