From f01862dddfb3fe12c6931546a58313f7223d6df5 Mon Sep 17 00:00:00 2001 From: newt Date: Wed, 9 Oct 2024 18:10:09 +0100 Subject: [PATCH] feat(problem): 9 - special pythagorean triplet --- readme.md | 6 +++--- src/bin/9.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 src/bin/9.rs diff --git a/readme.md b/readme.md index d2af165..9d66936 100644 --- a/readme.md +++ b/readme.md @@ -9,7 +9,7 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom ## Challenge Completion -8 out of 100 public challenges completed. +9 out of 100 public challenges completed. - [x] 1 - [Multiples of 3 or 5](src/bin/1.rs) - [x] 2 - [Even Fibonacci numbers](src/bin/2.rs) @@ -19,7 +19,7 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom - [x] 6 - [Sum square difference](src/bin/6.rs) - [x] 7 - [10001st prime](src/bin/7.rs) - [x] 8 - [Largest product in a series](src/bin/8.rs) -- [ ] 9 - Special Pythagorean triplet +- [x] 9 - [Special Pythagorean triplet](src/bin/9.rs) - [ ] 10 - Summation of primes - [ ] 11 - Largest product in a grid - [ ] 12 - Highly divisible triangular number @@ -110,4 +110,4 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom - [ ] 97 - Large non-Mersenne prime - [ ] 98 - Anagramic squares - [ ] 99 - Largest exponential -- [ ] 100 - Arranged probability +- [ ] 100 - Arranged probability \ No newline at end of file diff --git a/src/bin/9.rs b/src/bin/9.rs new file mode 100644 index 0000000..c8df94b --- /dev/null +++ b/src/bin/9.rs @@ -0,0 +1,41 @@ +/* +Problem 9 - Special Pythagorean triplet + +A Pythagorean triplet is a set of three natural numbers, a < b < c , for which, +a 2 + b 2 = c 2 +For example, 3 2 + 4 2 = 9 + 16 = 25 = 5 2 . +There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc . +*/ + +//! Notes: +// a + b + c = n +// c = n - a - b + +// a^2 + b^2 = c^2 +// a^2 + b^2 = (n - a - b)^2 +// 0 = 2ab - 2an - 2bn + n^2 +// 2an - n^2 = b(2a - 2n) +// b = (2an - n^2)/(2a - 2n) + +// For a given value a, with a sum of n +// b = (2an - n^2)/(2a - 2n) +// c = n - a - b + +fn triplet_with_sum(sum: isize) -> (isize, isize, isize) { + for a in 1..(sum + 1) { + let b: isize = ((2 * a * sum) - sum.pow(2)) / (2 * (a - sum)); + let c: isize = sum - a - b; + + if a.pow(2) + b.pow(2) == c.pow(2) { + return (a, b, c); + } + } + + panic!("A triplet could not be found with the sum {sum}!"); +} + +fn main() { + let (a, b, c) = triplet_with_sum(1000); + + println!("a = {a}, b = {b}, c = {c} // abc = {}", a * b * c); +}