I am having a number N i want to divide this number into sum of square contains upto 4 numbers.
For Ex:
120 = 8^2 + 6^2 + 4^2 + 2^2
6 = 0^2 + 1^2 + 1^2 + 2^2
20 = 4^2 + 2^2+ 0^2+ 0^2
My approach
Take Square root every time
while(count!=4){
root = (int) Math.sqrt(num)
num-=root*root
count++
}
But this fails for N=23 , is there any theorem to do that ?
For N=23
Ans = 3^2 + 3^2+ 2^2+ 1^2
Here is an exercise from the book, A Course in Computational Number Theory, by David Bressoud and me.
I have Mathematica code for this and it takes only an eye blink to do this:
Stan Wagon, author: A Course in Computational Number Theory, Mathematica in Action
Edit: You asked for a theorem. Lagrange proved many years ago that every number is a sum of four squares. So of course a very slow algorithm is to check all possibilities! The algorithm I mentioned above is very very fast.