Reputation: 11
i was asked to create an algorithm that prints all the possible combinations for the equation a^n+b^n=c^n without duplicates. the given input was a limit and the pow of the numbers. i used 3 nested loops in order to solve this(no complicity limits) but i couldn't solve the duplicates problem. for example,
input: 2(pow),20(limit)
my output: 3,4,5
4,3,5
5,12,13
6,8,10
8,6,10
8,15,17
9,12,15
12,5,13
12,9,15
12,16,20
15,8,17
16,12,20
correct output:
3,4,5
5,12,13
6,8,10
8,15,17
9,12,15
public static void Fermat(int n,int range) {
int temp = 0;
double x, y, z;
for (int a = 1; a <= range; a++) {
for (int b = 1; b <= range; b++) {
for (int c = 1; c <= range; c++) {
x = Math.pow(a, n);
y = Math.pow(b, n);
z = Math.pow(c, n);
if (x + y == z) {
System.out.println(a + "," + b + "," + c);
}
}
}
}
}
Upvotes: 1
Views: 97
Reputation: 7279
Try tightening your restrictions:
for (int a = 1; a <= range; a++) {
for (int b = a; b <= range; b++) {
for (int c = b; c <= range; c++) {
...
Upvotes: 1