Home>

On Lagrange's Four Square Theorem

Error message

There are 4 integers, but there are duplicate combinations.
I want to eliminate this duplication.

Applicable source code include

int main (void) {
int a, b, c, d, m, h, i, j, k;
int cun = 0;
printf ("Please enter an integer. n =");
scanf ("% d",&m);
puts ("4 integer pairs are \ n");
for (h = 0;h * h<= m;h ++) {
a = h * h;
for (i = 0;i * i + h * h<= m;i ++) {
b = a + i * i;
for (j = 0;j * j + i * i + h * h<= m;j ++) {
c = b + j * j;
for (k = 0;k * k + j * j + i * i + h * h<= m;k ++) {
d = c + k * k;
if (d == m) {
printf ("% d% d% d% d \ n", h, i, j, k);
cun ++;
}
}
}
}
}
printf ("Solution combination is% d", cun);
return (0);
}

I tried using break and do statements, but I didn't understand.

c
  • Answer # 1

    I think that it is quick to adjust the loop start condition so that

    h<= i<= j<= k.

    for (h = 0;h * h<= m;h ++) {
      a = h * h;
      for (i = h;i * i + h * h<= m;i ++) {
        b = a + i * i;
        for (j = i;j * j + i * i + h * h<= m;j ++) {
          c = b + j * j;
          for (k = j;k * k + j * j + i * i + h * h<= m;k ++) {
            d = c + k * k;

  • Answer # 2

    I just think.

    The 4 integers (h, i, j, k) obtained are arranged in order from the largest and stored.
    So, it is determined whether there is the same combination before memorizing, and if it is not memorized, there will be no duplication.
    Or, it sorts 4 integers, but it is okay to duplicate them, so it is memorized unconditionally, and it is displayed after removing duplicates before displaying.