Is there any way to represent any number as sum of 4 squares.
For example 29 can be represented as 5^2+2^2+0^2+0^2
I tried the following code but some numbers giving 5terms for example 23 as 4^2+2^2+1^2+1^2+1^2
the code i tried is :
x=0;
while(num!=0){
x=(int)Math.floor(Math.sqrt(num));
num=num-(x*x);
}
All positive integers can be expressed as sums of squares. Some can be expressed as the sum of two or three squares, some can be expressed as the sum of a million squares. And some can be expressed expressed as sums of squares in multiple ways. For example, 338350 is the sum of the first hundred nonzero squares.
Sum of Squares Formulas and Proofs If n consecutive natural numbers are 1, 2, 3, 4, …, n, then the sum of squared 'n' consecutive natural numbers is represented by 12 + 22 + 32 + … + n2.
Informally: When you multiply an integer (a “whole” number, positive, negative or zero) times itself, the resulting product is called a square number, or a perfect square or simply “a square.” So, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, and so on, are all square numbers.
Unlike what Bohemian said, I solved 23 in 4 terms as follows:
23 = 3^2 + 3^2 + 2^2 + 1^2
And 29 as follows:
29 = 4^2 + 3^2 + 2^2 + 0^2
My logic would start as:
SQRT(29) = 5 - 1 = 4;
This is now our first term.Note: This is for your simple case. For complex case like e.g. 323, this might not work.
323 = 17^2 + 4^2 + 3^2 + 3^2
Bear in mind, as you find the x term, the term's value is less than or equal to the x-1 (previous) term's value.
Here is the algorithm code for you
This will give you all possible combinations ...
int n, t1, t2, t;
n = 29;//Your number
for (int i = (int) Math.sqrt(n / 4); i * i <= n; i++) {
t1 = n - i * i;
for (int j = (int) Math.sqrt(t1 / 3); j <= i && j * j <= t1; j++) {
t2 = t1 - j * j;
for (int k = (int) Math.sqrt(t2 / 2); k <= j && k * k <= t2; k++) {
t = (int) Math.sqrt(t2 - k * k);
if (t <= k && t * t == t2 - k * k) {
System.out.println("(" + i + "^2) + (" + j + "^2) + ("+ k + "^2) + ("+ t +"^2)");
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With