Isqrt (integer square root) of X: Difference between revisions
Content added Content deleted
(Added Algol W) |
|||
Line 542: | Line 542: | ||
=={{header|ALGOL-M}}== |
=={{header|ALGOL-M}}== |
||
The |
The code presented here follows the task description. But be warned: there is a bug lurking in the algorithm as presented. The statement q := q * 4 in the first while loop will overflow the limits of ALGOL-M's integer data type (-16,383 to +16,383) for any value of x greater than 4095 and trigger an endless loop. The output has been put into columnar form to avoid what would otherwise be an ugly mess on a typical 80 column display. |
||
<syntaxhighlight lang="algol"> |
<syntaxhighlight lang="algol"> |
||
BEGIN |
BEGIN |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
BEGIN |
BEGIN |
||
INTEGER |
INTEGER Q, R, Z, T; |
||
Q := 1; |
|||
WHILE Q <= X DO |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
BEGIN |
BEGIN |
||
Q := Q / 4; |
|||
T := Z - R - Q; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
END; |
END; |
||
ISQRT := |
ISQRT := R; |
||
END; |
END; |
||
⚫ | |||
COMMENT - LET'S EXERCISE THE FUNCTION; |
COMMENT - LET'S EXERCISE THE FUNCTION; |
||
Line 592: | Line 605: | ||
END |
END |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
An alternative to the quadratic residue approach will allow calculation of the integer square root for the full range of signed integer values supported by ALGOL-M. (The output is identical.) |
|||
But for those for whom only the quadratic residue algorithm will do, just substitute this for the ISQRT() function in the previous example. (The output is identical.) But be warned: there is a bug lurking in the algorithm as presented in the task description. The statement q := q * 4 in the first while loop will overflow the limits of ALGOL-M's integer data type (-16,383 to +16,383) for any value of x greater than 4095 and trigger an endless loop. |
|||
<syntaxhighlight lang="algol"> |
<syntaxhighlight lang="algol"> |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
BEGIN |
BEGIN |
||
INTEGER |
INTEGER R1, R2; |
||
R1 := N; |
|||
R2 := 1; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
BEGIN |
BEGIN |
||
R1 := (R1+R2) / 2; |
|||
R2 := N / R1; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
END; |
END; |
||
ISQRT := |
ISQRT := R1; |
||
END; |
END; |
||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> |
<pre> |