0
$\begingroup$

Given (n) , what is the Count of (x,y) pairs that satisfy the equation x^2+y^2 = n^2. Is there any way I can re-write this code just without using nested loop?

int counter=0;
    int x=0;


    for (int i =(int) n-1; i>=0 ; i--){

        if(i == x)
            break;


        for (int j = 1; j< (int)n ; j++){

            if (Math.pow(i,2)+Math.pow(j,2) == Math.pow(n,2)){
                counter++;
                x = j;
            }
        }
    } 
System.out.print(counter);
$\endgroup$
  • $\begingroup$ This question looks like off-topic. Any way, it fits Stack Overflow probably more. $\endgroup$ – Apass.Jack Mar 20 at 3:43
3
$\begingroup$

Your approach is to try every possible $x$ and $y$ and see if $x^2+y^2=n^2$. However, $n$ is fixed and, for any $x$, either $n^2-x^2$ is a perfect square or it isn't. You can calculate what $y$ is, instead of looping and trying every possible value.

Actual code is off-topic but it's confusing that you're trying to solve a problem about $x$ and $y$, but you've represented those quantities in variables called i and j. And even worse that you have a variable called x that represents something else entirely. (In fact, I'm not sure it's even correct. You seem to be using x to avoid reporting, e.g., $x=3$, $y=4$ and $x=4$, $y=3$ as separate solutions for $n=5$. But they are separate solutions and the question, at least as you've summarized it, doesn't say that they should be counted as the same.)

$\endgroup$
  • $\begingroup$ I'm new at java and I apologize for the inconvenience, I agree with about getting x , but I don't know how I should write it as a code. $\endgroup$ – Victoria Mar 10 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.