Mroweczka - 1 year ago 67
C++ Question

# True/False function if a sum exists

I want to have a program that returns true when there exist such positive integer numbers

`a`
and
`b`
such that
`a*a+b*b=n*n`
.

My code is:

`````` bool c(int n){
int b=1;
int a=1;
for (a=1; a<=n; a++) {
for (b=a; b<=n; b++) {
if (a*a + b*b == n*n) {
return true;
else
return false;
}
}

}
``````

However this code does not return what i want it to. What can i do to fix that?

Please everybody before you down vote please explain what could be improved in this question. I have noticed that sometimes people have a tendency to down vote questions without any explanation.

Your program doesn't compile. You probably intended to write this:

``````bool c(int n) {
int b = 1;
int a = 1;
for (a = 1; a <= n; a++) {
for (b = a; b <= n; b++) {
if (a*a + b*b == n*n)
return true;
else
return false;
}
}
}
``````

which compiles, but which is wrong.

But you probably want this:

``````bool myfunction(int n) {
int b = 1;
int a = 1;
for (a = 1; a <= n; a++) {
for (b = a; b <= n; b++) {
if (a*a + b*b == n*n)
return true;
}
}

return false;
}

int main() {
if (myfunction(5)) {
printf("myfunction(5) returned true\n");
}
}
``````