feat(problem): 9 - special pythagorean triplet

This commit is contained in:
newt 2024-10-09 18:10:09 +01:00
parent 5b18aab18d
commit f01862dddf
2 changed files with 44 additions and 3 deletions

View file

@ -9,7 +9,7 @@ All of the solutions here are written in rust. [main.rs](src/main.rs) is the hom
## Challenge Completion
<!-- completed -->8<!-- completed --> out of 100 public challenges completed.
<!-- completed -->9<!-- completed --> 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

41
src/bin/9.rs Normal file
View file

@ -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);
}