0
$\begingroup$

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

1 Answers 1

4

Here is an exercise from the book, A Course in Computational Number Theory, by David Bressoud and me.

Fill in the proofs and implement the following method, due to Rabin and Shallit, for finding a single representation of $n$ as a sum of four squares. Given $n \equiv 2 \pmod 4$, subtract a pair of randomly chosen squares from $n$ and check if the result is a prime. If it is, it must be $1 \pmod 4$ and we can represent it as a sum of two squares, using a very well known method. This gives four squares that sum to $n$. If the result of the subtraction is not prime, try subtracting a different pair of squares. If $n \equiv 0 \pmod 4$, use recursion on $n/4$ and multiply each entry in the answer by $2$. If $n$ is odd, use recursion on $2n$; the result must have two even entries and two odd entries. Let the even ones be $r$ and $s$ and let $a$ and $b$ be the others, with $s>r$ and $b>a$. Then $(s+r)/2, (s-r)/2, (b+a)/2$, and $(b-a)/2$ solve the problem for $n$.

I have Mathematica code for this and it takes only an eye blink to do this:

SumOfFourSquares[123456789123456789123456789123456789]

{25120491765750065, 131539721845738992, 155860771536239540, 285009598943224070}

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.