There is Lagrange's four-square theorem, which statea that
Given an integer $N$, we can write $N$ as a sum of four squares $A^2+B^2+C^2+D^2=N$.
How can I find a valid solution with time complexity of $O(1)$ or $O(\sqrt N)$? I only have to find one solution.
Here is my $O(1)$ algorithm:
while(count!=4){
solution = sqrt(N)
print solution
N-= solution*solution
count++
}
But it does not works for all $N$, for example it fails for $N=23$. Is there any other solution?