Skip to main content
Library homepage
 
Engineering LibreTexts

6.7: Putting It Together

  • Page ID
    86205
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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.7: Putting It Together is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.