1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
/*
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
*/
/*
If: a + b + c = 1000, and: a^2 + b^2 = c^2, then:
a^2 + b^2 = (1000 - a - b)^2.
Expanded: a^2 + b^2 = (1000 - a - b) * (1000 - a - b).
Foiled: a^2 + b^2 = 1000^2 + a^2 + b^2 - 2000a - 2000b + 2ab.
Subracting (a^2 + b^2): 0 = 1000^2 - 2000a - 2000b + 2ab.
Dividing by -2000: a + b - (ab / 1000) - 500 = 0.
If b is isolated: b * (1 - a / 1000) = (-a + 500).
b becomes eliminated: b * (1 - a / 1000) * (1 + 1000 / a) = (-a + 500) * (1 + 1000 / a).
Foiled: -a - 1000 + 500 + 500'000 / a = 0.
Multiplied by -a: a^2 + 500a -500,000 = 0.
The quadratic equation: (-b +- (b^2 - 4 * a * c)^(1/2)) / (2 * a)
The answer asked for: a = 200, b = 375, c = 425, product = 31'875'000.
*/
#include <iostream>
#include <complex>
#include <math.h>
#include <locale>
// quadraticType holds positive and negative solutions for a quadratic equation
struct quadraticType {
std::complex<double> positive;
std::complex<double> negative;
};
quadraticType solution(std::complex<double>, std::complex<double>, std::complex<double>);
int main()
{
std::complex<double> quadA = 1.0, quadB = 500, quadC = -500'000;
quadraticType answerSet = solution(quadA, quadB, quadC);
int a = static_cast<int>(answerSet.positive.real());
int b = static_cast<int>(answerSet.negative.real());
int c = 1000 - a - b;
int product = a * b * c;
std::cout.imbue(std::locale(""));
std::cout << "Answer: " << product << std::endl;
std::cout << std::endl;
}
quadraticType solution(std::complex<double> a, std::complex<double> b, std::complex<double> c) {
quadraticType answerSet;
std::complex<double> rootPart = sqrt(pow(b, 2) - 4.0 * a * c);
std::cout << "root part: " << rootPart << std::endl;
answerSet.positive = (-b + rootPart) / (2.0 * a);
answerSet.negative = (-b - rootPart) / (2.0 * a);
return answerSet;
}
|