Pythagorean Triples

VSBrown 0 Tallied Votes 2K Views Share

Find all Pythagorean triples for side1, side2 and hypotenuse in which all sides are no larger than 500. Use a triple nested for loop that tries all possibilites.

/******************************************************

** Name: 

** Filename: ptriples.cpp

** Project #: Deitel & Deitel 2.55

** Project Description: Find all Pythagorean triples for side1,
   side2 and hypotenuse in which all sides are no larger than 
   500. Use a triple nested for loop that tries all possibilites.

** Output: All Pythagorean triples for side1,
   side2 and hypotenuse in which all sides are no larger than 
   500.

** Input: None

** Algorithm: Instruct user of process to be performed.
    If 500 or less then calculate using formula a^2 + b^2 = c^2 
   by running 3 loops to find all posible combinations
   When combination equals a^2 + b^2 = c^2 then print out results,
   and add up the number of solutions and print out solutions at 
   the end.
   End program

******************************************************/

// Include files
#include <iostream>  // used for cin, cout
#include <conio.h>
using namespace std;

// Global Type Declarations

// Function Prototypes
void instruct (void);
void pause ();

//Global Variables - should not be used without good reason.

int main ()
{
	 // Declaration section
	int side1,        // Side 1 of triangle
		side2,        // Side 2 of triangle
		hyp,          // Hypotenuse of triangle
	    sols = 0;     // Number of pythogorean triples solutions
	   
	 
	 // Executable section
	 instruct ();



    cout << "\nPossible combinations are:\n\n";

	for (side1 = 1; side1 <= 500; side1++) {

    for (side2 = 1; side2 <= 500; side2++) {

    for (hyp = 1; hyp <= 500; hyp++) {

		if (( side1 * side1 + side2 * side2) == hyp * hyp ){
			
			cout << side1 << "\t" << side2 << "\t" << hyp << "\n";
		    ++sols;
        if ( sols % 10 == 0 )
			pause ();
				
	}
	}
	}
   
	}


     cout << "\nThere is a total of " << sols << " possible solutions" 
		  << endl ;

	 pause ();
	 return 0;
}

void instruct (void)
{
	  // Declaration section
      cout << "This program will find all Pythagorean triples for\n" 
		   << "side1, side2 and hypotenuse in which all sides are no\n" 
		   << "larger than 500" << endl ;
	  
	  // Executable section
}

void pause ()
{
    // Declaration section

    // Executable section
    cout << "\nPress any key to continue...";
    getch();
    cout << "\r";
    cout << "                            ";
    cout << "\r";
}


/*
Program Output

This program will find all Pythagorean triples for
side1, side2 and hypotenuse in which all sides are no
larger than 500

Possible combinations are:

3       4       5
4       3       5
5       12      13
...     ...     ...
480     108     492
480     140     500
483     44      485

There is a total of 772 possible solutions

Press any key to continue...



*/

Dani AI

Generated

Good start, . The triple nested loop is simple and correct, but it does a lot of redundant work and prints both orderings of the same triangle (for example (3,4,5) and (4,3,5)). Two quick, practical improvements: (1) avoid permutations by making side2 start at side1 (so side1 <= side2), and (2) remove the innermost loop and test the hypotenuse with an integer square-root check (compute c2 = aa + bb, then use an integer sqrt and verify c*c == c2). That drops work from roughly O(n^3) to O(n^2) and keeps everything integer-safe. For portability, avoid nonstandard console headers; use standard input/output for pauses.

A more efficient approach that also produces only unique triples is Euclid's formula: generate primitive triples from coprime (m,n) with opposite parity, then scale them by k. Example Python generator (returns sorted, unique triples):

import math

def gen_triples(limit=500):
    triples = set()
    max_m = int(math.sqrt(limit)) + 1
    for m in range(2, max_m):
        for n in range(1, m):
            if (m - n) % 2 == 1 and math.gcd(m, n) == 1:
                a, b, c = m*m - n*n, 2*m*n, m*m + n*n
                if c > limit:
                    continue
                k = 1
                while a*k <= limit and b*k <= limit and c*k <= limit:
                    triples.add(tuple(sorted((a*k, b*k, c*k))))
                    k += 1
    return sorted(triples)

Notes: sorting each triple before adding to the set gives a canonical (a <= b < c) form; use a set to deduplicate. If you need both ordered permutations, print both (a,b,c) and (b,a,c) when you output. For modest limits (like 500) overflow is not an issue; for much larger limits use appropriate integer types and watch time complexity.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.