optimize 94

This commit is contained in:
Dr. Matthias Ratajczak
2023-06-27 18:25:01 +02:00
parent 99c64ad172
commit 0009062486
+22 -32
View File
@@ -1,34 +1,32 @@
use f128::f128; type Num = usize;
use num_traits::Float;
type Num = f128;
static mut ONE_BILLION: Num = f128::ZERO;
const ONE: Num = f128::ONE;
fn main() { fn main() {
unsafe { let mut sum = 0;
ONE_BILLION = f128::from(1_000_000_000.);
}
let mut sum = f128::ZERO; let mut i = 5;
'outer: loop {
if i > 333_333_334 {
break;
}
let a = i;
'outer: for i in 2.. { if a % 2 == 0 {
let a = f128::from(i); i += 1;
continue;
}
for c in [a - ONE, a + ONE] { for c in [a - 1, a + 1] {
let t = Triangle::new(a, c); let t = Triangle::new(a, c);
let p = t.perimeter();
if unsafe { p > ONE_BILLION } {
break 'outer;
}
if t.has_integer_area() { if t.has_integer_area() {
println!("{:.10}, {:.10}", t.a, t.c); println!("{:.10}, {:.10}", t.a, t.c);
sum += p; sum += t.perimeter();
i = ((i as f64) * 3.59).trunc() as usize;
continue 'outer;
} }
} }
i += 1;
} }
println!("{sum:.15}"); println!("{sum:.15}");
@@ -45,21 +43,13 @@ impl Triangle {
} }
fn perimeter(&self) -> Num { fn perimeter(&self) -> Num {
Num::TWO * self.a + self.c 2 * self.a + self.c
} }
fn has_integer_area(&self) -> bool { fn has_integer_area(&self) -> bool {
is_integer(self.area()) let h = 4 * self.a.pow(2) - self.c.pow(2);
} let root = (h as f64).sqrt().trunc() as usize;
fn area(&self) -> Num { root * root == h
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: Num) -> bool {
(x.round() - x).abs() <= Num::EPSILON
}