Pythagorean Triples

Okay, I'm hunting down Pythagorean triples. Both the natural ones, and the multiples.

What I would like, is to read in a value n, and then output every pythagorean triple for which the values <a,b,c> are less than or equal to n.

I have a working program. However, if you run this code and then compare it to the list here
http://www.tsm-resources.com/alists/trip.html
you will notice that there are slight discrepancies. Not every multiple on that list, is found by my program. It's almost perfect, but I would like to at least understand why some are missing. My code is simple, so I will post it in its entirety.

If you can help me understand why, I would greatly appreciate it. If it's an issue with my code I am happy to make changes, feel free to suggest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	int n;

	cout << "a*a + b*b = c*c" << endl
	     << "a,b,c are all integers" << endl
	     << "a,b,c are all less than or equal to n" << endl
	     << "Please input n: ";

	cin >> n;

	cout << "You have chosen to find all pythagorean triples < or = to " 
	     << n 
	     << "."
	     << endl;
    
    for(int i = 1; i<=n; i++)
    {
    	for(int j = i; j<=n; j++)
    	{
    		double thing1 = sqrt((i*i)+(j*j));
    		int thing2 = thing1;
    		if( ((i*i)+(j*j)) <= (n*n) && thing1 == thing2)
    		{
    			cout << "(" 
    				 << i 
    				 << ", " 
    				 << j 
    				 << ", "
    				 << sqrt((i*i)+(j*j)) 
    				 <<  ")" 
                     << endl;
    		}
    	}
    }
  return(0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n;

    cout << "a*a + b*b = c*c\n"
         << "a,b,c are all integers\n"
         << "a,b,c are all less than or equal to n\n"
         << "Please input n: ";

    cin >> n;

    cout << "You have chosen to find all pythagorean triples < or = to "
         << n << ".\n" ;

    for( int c = 1 ; c <= n ; ++c )  // for c in 1 ... n
    {
        const int csquared = c * c ;
        const int ubound = sqrt(csquared) + 1.1 ; // safe

        for( int a = 1 ; a < ubound ; ++a ) // for a in 1 ... sqrt(csquared)
        {
            for( int b = a+1 ; b < ubound ; ++b ) // for b in a+1 ... sqrt(csquared)
            {
                if( ( (a*a) + (b*b) ) == csquared ) // if a*a + b*b == c*c
                {
                    cout << "(" << a << ", " << b << ", " << c <<  ")\n" ;
                    break ;
                }
            }
        }
    }
}
Your program finds all triples. The lists are just sorted differently.
Topic archived. No new replies allowed.