vforbiedronka - 1 year ago 73

C Question

I want to count how many pairs of natural number there are such that a^{2} + b^{2} = c^{2}. 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`

`c`

`count++`

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.

Answer Source

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.