#include <stdio.h>
void printCombs(int n) {
int i, j, limit = ceil(sqrt(n));
for(i = 1; i < limit; i++) {
for(j = i; j < limit; j++) {
if(i*i + j*j == n) {
printf("%d,%d\n", i, j);
printf("%d,", j);
printCombs(i*i);
printf("\n%d,", i);
printCombs(j*j);
printf("\n");
}
}
}
}
int main() {
int n;
scanf("%d", &n);
printCombs(n);
return 0;
}
I have written this code which outputs combinations of numbers whose sum of squares equals the given input. The code is working fine but the problem is with the not-wanted output.
For example I enter 1000:
1000
10,30
30,6,8
8,
6,
10,18,24
24,
18,
18,26
26,
18,10,24
24,6,8
8,
6,
10,
First I get 10,30 which is fine because 100+900 = 1000.
Then 30, 6, 8 => 900+36+64 = 1000.
Then 10, 18, 24 => 100 + 324 + 576 = 1000.
Then 18, 26 => 324 + 676 = 1000.
Then 18, 10, 24 => 576 + 100 + 324 = 1000.
Now these are all the combinations. But as you can see there are some other number output also on the screen which are due to the printf()
before the recursive calls which do not output anything. And in the end when it outputs 24, 6, 8
.`. I am not being able to figure out how to prevent this from output-ing. How do I just print those combinations? Any help is appreciated thanks.
printf("%d,", j);
, you would needsprintf
). – Jarod423 = 1²+1²+1²
but cannot be written asa²+b²
... – Jarod42