# Lagrange’s four square theorem in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn about largrange's four square theorem.

The lagranges's four square theorem states that every natural number can be written as sum of squares of 4 numbers.

The following code finds the 4 numbers which satisfies the above condition for the given number n.

## Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
void printSquareCombinations(int n) {
for (int i = 0; i * i <= n; i++) {
for (int j = i; j * j <= n; j++) {
for (int k = j; k * k <= n; k++) {
for (int l = k; l * l <= n; l++) {
if (i * i + j * j + k * k + l * l == n) {
cout << n << " = " << i << "*" << i << " + " << j << "*" << j << " + " << k << "*" << k << " + "<< l << "*" << l << endl;
}
}
}
}
}
}
int main() {
int n = 25;
printSquareCombinations(n);
return 0;
}

## Output

If you run the above code, then you will get the following result.

25 = 0*0 + 0*0 + 0*0 + 5*5
25 = 0*0 + 0*0 + 3*3 + 4*4
25 = 1*1 + 2*2 + 2*2 + 4*4

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.