From 99c64ad172279e8fe15db920c1e9321246e25a1d Mon Sep 17 00:00:00 2001 From: "Dr. Matthias Ratajczak" Date: Tue, 27 Jun 2023 17:41:58 +0200 Subject: [PATCH] finish 94 --- src/euler94/Cargo.toml | 6 +++++ src/euler94/src/main.rs | 51 ++++++++++++++++++++++++++--------------- 2 files changed, 39 insertions(+), 18 deletions(-) diff --git a/src/euler94/Cargo.toml b/src/euler94/Cargo.toml index e197630..0f099c5 100644 --- a/src/euler94/Cargo.toml +++ b/src/euler94/Cargo.toml @@ -6,3 +6,9 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +f128 = "0.2.9" +num-traits = "0.2.15" + +[profile.release] +lto = "fat" +codegen-units = 1 diff --git a/src/euler94/src/main.rs b/src/euler94/src/main.rs index 127fa08..527b02f 100644 --- a/src/euler94/src/main.rs +++ b/src/euler94/src/main.rs @@ -1,50 +1,65 @@ -type Num = u64; +use f128::f128; +use num_traits::Float; -const ONE_BILLION: Num = 1_000_000_000; +type Num = f128; + +static mut ONE_BILLION: Num = f128::ZERO; +const ONE: Num = f128::ONE; fn main() { - let mut sum = 0 as Num; + unsafe { + ONE_BILLION = f128::from(1_000_000_000.); + } + + let mut sum = f128::ZERO; + 'outer: for i in 2.. { - let a_b = i as Num; - for c in [a_b - 1, a_b + 1] { - let t = Triangle::new(a_b, c); + let a = f128::from(i); + + for c in [a - ONE, a + ONE] { + let t = Triangle::new(a, c); let p = t.perimeter(); - if p > ONE_BILLION { + if unsafe { p > ONE_BILLION } { break 'outer; } if t.has_integer_area() { + println!("{:.10}, {:.10}", t.a, t.c); sum += p; } } } - println!("{sum}"); + println!("{sum:.15}"); } struct Triangle { - a_b: Num, + a: Num, c: Num, } impl Triangle { - fn new(a_b: Num, c: Num) -> Self { - Self { a_b, c } + fn new(a: Num, c: Num) -> Self { + Self { a, c } } fn perimeter(&self) -> Num { - 2 * self.a_b + self.c + Num::TWO * self.a + self.c } fn has_integer_area(&self) -> bool { - let a_b = self.a_b as f64; - let c = self.c as f64; - let area = c / 4. * (4. * a_b.powi(2) - c.powi(2)).sqrt(); - is_integer(area) + is_integer(self.area()) + } + + fn area(&self) -> Num { + let a = self.a; + let c = self.c; + + c / Num::from(4.) * (Num::from(4.) * a.powi(2) - c.powi(2)).sqrt() } } -fn is_integer(x: f64) -> bool { - (x.round() - x).abs() <= f64::EPSILON +fn is_integer(x: Num) -> bool { + (x.round() - x).abs() <= Num::EPSILON }