vforbiedronka vforbiedronka - 1 month ago 14
C Question

Sum of two squares decomposition counting

I want to count how many pairs of natural number there are such that a2 + b2 = c2. As an input to my function I have

c
.

My idea was to first check whether the condition is fulfilled, than if not, I wanted to have a loop iterating desired expression up to
c
. If result is equal to the square of
c
than I wanted to have
count++
. Question is why this is not working?

Some corrections added.

int sum(int c) {
int b=1;
int a=1;
int count=0;
int result;

if (a*a + b*b != c*c)
{
for (int i=1; i<=c; i++)
{
b=i;
result = a*a + b*b;
if (result == c*c)
count++;
}
a++;
}
else
count++;

return count;
}


The problem is I still do not understand why this does not want to work.

My second idea was to approach it with while loop:

int sum(int c) {
int b=1;
int a=1;
int count=0;
int result;

if (a*a + b*b != c*c)
{
while(b<=c)
{
result = a*a + b*b;
if (result == c*c)
{count++;
b++;
}
else
b++;
}
a++;
}
else
count++;

return count;
}


Not working as well.

Anybody any ideas as to how to make it work? Any of those two versions? Maybe hints?

Answer

The problem is that you're using an if expecting it to work like a loop. At the bottom of the if you're incrementing a, however because it is an if and not a while or for, it doesn't jump back up to the top.

Both a and b need to change, so you need a loop to control each one.

for (a=1; a<=c; a++) {
    for (b=a; b<=c; b++) {
        if (a*a + b*b == c*c) {
            count++;
        }
    }
}

Note that b starts at the current value of a instead of 1. That way, you aren't trying the same pair of numbers (just switched) twice.

Comments