A 1000 Pythagorean triplets - 我的博客 - ITeye技术网站
http://www.mathblog.dk/pythagorean-triplets/
Read full article from A 1000 Pythagorean triplets - 我的博客 - ITeye技术网站
http://www.mathblog.dk/pythagorean-triplets/
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
Brute Force
For the brute force algorithm we would need to loop over all the possible values of a and b, calculatec and check if that is a solution. We could be ignorant and just let a and b loop from 1-1000, or we could use the facts that a < b < c, and thus exploit that a < s/3, and a < b < s/2.
- int a = 0, b = 0, c = 0;
- int s = 1000;
- bool found = false;
- for (a = 1; a < s / 3; a++) {
- for (b = a; b < s / 2; b++) {
- c = s - a - b;
- if (a * a + b * b == c * c) {
- found = true;
- break;
- }
- }
- if (found) {
- break;
- }
- }
Read full article from A 1000 Pythagorean triplets - 我的博客 - ITeye技术网站