My assignment says to do the following:
Search2: Search for a solution to x*x + y*y – 12x -10y + 36 = 0. Search from 0 to 10 in both x and y, searching every y value before moving to the next x. Print the first three solutions found. (Note – a labelled break is handy here!)
I can’t figure out the logic for this. I think I have to use more than 2 loops but not sure.
This is what I have so far (It just repeats (6,0)):
for (int j = 0; j <= 10; j++) {
for (int i = 0; i <= 10; i++) {
while (((i * i) + (j * j) - (12 * i) - (10 * j) + 36) == 0) {
System.out.println("(" + i + ", " + j + ")");
}
}
}
UPDATE
Here is the solution:
int t = 0;
for (int i = 0; i <= 10; i++) {
if (t == 3) {
break;
}
for (int j = 0; j <= 10; j++) {
if (((i * i) + (j * j) - (12 * i) - (10 * j) + 36) == 0) {
System.out.println("(" + i + ", " + j + ")");
t++;
}
}
}
Not a bad attempt. Because you’re so close, I’ll show you a working solution. Basically, you need to do three things:
whiletoifI also recommend you use variable names the same as the problem – ie
xandy– for clarity.When executed, this code produces:
Sorry for spoon-feeding you, but part of the lesson here is good coding style and practice.