The algorithm is taken from great “Algorithms and Programming: Problems and Solutions” by Alexander Shen (namely exercise 1.1.28).
Following is my translation from Russian so excuse me for mistakes or ambiguity. Please correct me if you feel so.
What should algorithm do
With given natural n algorithm calculates the number of solutions of
inequalityx*x + y*y < nin natural (non-negative) numbers without using
manipulations on real numbers
In Pascal
k := 0; s := 0;
{at this moment of execution
(s) = number of solutions of inequality with
x*x + y*y < n, x < k}
while k*k < n do begin
l := 0; t := 0;
while k*k + l*l < n do begin
l := l + 1;
t := t + 1;
end;
{at this line
(t) = number of solutions of k*k + y*y < n
for given (k) with y>=0}
k := k + 1;
s := s + t;
end;
{k*k >= n, so s = number of solutions of inequality}
Further in the text Shen says briefly that number of operations performed by this algorithm is “proportional to n, as one can calculate”. So I ask you how one can calculate that with strict mathematics.
You have two loops, one inside the other.
The external has this condition:
k*k < nsokgoes from0up toSQRT(n)and the internal loop has this condition:
k*k + l*l < nsolgoes from0up toSQRT(n-k^2). But this is snaller thanSQRT(n)So, the maximum iterations is less than
SQRT(n) * SQRT(n)which isnand in every iteration a constant number of operations is done.