Generating all possible combinations of numbers under a certain number.

Oct 23, 2016 at 1:53pm
So im writing a program which finds pythagorean triples. I need to find a way to test out every single combination i can have with three numbers, all of them being under say 500, with the constraint that the last number in the three is always greater than the two before it.
Heres what ive got so far.
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
#include <iostream>
using namespace std;

bool check();
int a, b, c;

int main()
{
	while (1)
	{
		check();
		if (check() == true)
		{
			cout << a << " " << b << " " << c << endl;
		}
	}
}

bool check()
{
	if (sqrt((a*a) + (b*b))==c)
	{
		return true;
	}
	else
	{
		return false;
	}
}
Last edited on Oct 23, 2016 at 1:54pm
Oct 23, 2016 at 2:50pm
for(int a=1; a<limit; ++a)
Oct 24, 2016 at 12:02pm
The code you have given ne555, doesnt it just increment a by one after each iteration of the program? So it wouldnt actually combine all the possibilities of a,b and c.
Oct 24, 2016 at 12:24pm
You are right, one loop merely iterates through a list of values, but it also gives us the possibility to do something with each value.

You could have a different loop inside that loop, for b.

Inside the inner loop you will have a pair of (a,b), where a<=b. If you do adjust the boundaries of both loops correctly, then same pair will not occur more than once.

You can test that by printing every pair (for small upper limit).

If you do have a and b, then you can calculate the c; no need for third loop.
Oct 24, 2016 at 3:25pm
Hello @billy606, it seems you've started two threads for the same problem. Never mind, I just wanted to draw your attention to my post to the other thread here:

http://www.cplusplus.com/forum/general/200504/
Topic archived. No new replies allowed.