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)

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

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

1 Answer 1


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.)

  • $\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, 2019 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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