Opening the book…
Now instead of displaying all of the triples, we’ll add an if statement and display only Pythagorean triples:
for a=1:3
for b=1:4
for c=1:a+b
if is_pythagorean(a, b, c)
disp([a,b,c])
end
end
end
end
The result is just one triple:
>> find_triples
3 4 5
You might notice that we’re wasting some effort here. After checking the case when a is 1 and b is 2, there’s no point in checking the case when a is 2 and b is 1. We can save the extra work by adjusting the range of b:
for b=a:4
We can save even more work by adjusting the range of c:
for c=b:a+b
Here’s the final version:
for a=1:3
for b=a:4
for c=b:a+b
if is_pythagorean(a, b, c)
disp([a,b,c])
end
end
end
end
This page titled 6.6: Putting It Together was last modified on Thu, 17 Nov 2022 18:18:58 GMT and is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.
The book could not be loaded just now.