From 1e93703c61d944c90c19a909ed808f2d62ce14df Mon Sep 17 00:00:00 2001 From: "Dr. Matthias Ratajczak" Date: Tue, 27 Jun 2023 16:48:14 +0200 Subject: [PATCH] add 94 (WIP) --- src/euler94/Cargo.toml | 8 +++++++ src/euler94/src/main.rs | 50 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 src/euler94/Cargo.toml create mode 100644 src/euler94/src/main.rs diff --git a/src/euler94/Cargo.toml b/src/euler94/Cargo.toml new file mode 100644 index 0000000..e197630 --- /dev/null +++ b/src/euler94/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "euler94" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/euler94/src/main.rs b/src/euler94/src/main.rs new file mode 100644 index 0000000..127fa08 --- /dev/null +++ b/src/euler94/src/main.rs @@ -0,0 +1,50 @@ +type Num = u64; + +const ONE_BILLION: Num = 1_000_000_000; + +fn main() { + let mut sum = 0 as Num; + '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 p = t.perimeter(); + + if p > ONE_BILLION { + break 'outer; + } + + if t.has_integer_area() { + sum += p; + } + } + } + + println!("{sum}"); +} + +struct Triangle { + a_b: Num, + c: Num, +} + +impl Triangle { + fn new(a_b: Num, c: Num) -> Self { + Self { a_b, c } + } + + fn perimeter(&self) -> Num { + 2 * self.a_b + 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) + } +} + +fn is_integer(x: f64) -> bool { + (x.round() - x).abs() <= f64::EPSILON +}