6.9: Adding a continue Statement
- Page ID
As a final improvement, let’s modify the function so it only displays the “lowest” of each Pythagorean triple, and not the multiples.
The simplest way to eliminate the multiples is to check whether
b share a common factor. If they do, dividing both by the common factor yields a smaller, similar triangle that has already been checked.
MATLAB provides a
gcd function that computes the greatest common divisor of two numbers. If
gcd(a,b) is greater than 1,
b share a common factor and we can use the
continue statement to skip to the next pair. Listing 6.1 contains the final version of this function:
Listing 6.1: Our final Pythagorean triples function
function res = find_triples(n) for a=1:n for b=a:n for c=b:a+b if gcd(a,b) > 1 continue end if is_pythagorean(a, b, c) disp([a,b,c]) end end end end end
continue statement causes the program to end the current iteration immediately, jump to the top of the loop, and “continue” with the next iteration.
In this case, since there are three loops, it might not be obvious which loop to jump to, but the rule is to jump to the innermost loop (which is what we want).
Here are the results with
n = 40:
>> find_triples(40) 3 4 5 5 12 13 7 24 25 8 15 17 9 40 41 12 35 37 20 21 29