Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X

View file

@ -0,0 +1,97 @@
Sometimes a function is needed to find the integer square root of   '''X''',   where   '''X'''   can be a
real non─negative number.
Often   '''X'''   is actually a non─negative integer.
For the purposes of this task,   '''X'''   can be an integer or a real number,   but if it
simplifies things in your computer programming language,   assume it's an integer.
One of the most common uses of &nbsp; '''<code>Isqrt</code>''' &nbsp; is in the division of an integer by all factors &nbsp; (or
primes) &nbsp; up to the &nbsp; <big><span style="white-pace: nowrap; font-size:larger">
&radic;<span style="text-decoration:overline;">&nbsp;X&nbsp;</span></span> </big> &nbsp; of that
integer, &nbsp; either to find the factors of that integer, &nbsp; or to determine primality.
An alternative method for finding the &nbsp; '''<code>Isqrt</code>''' &nbsp; of a number is to
calculate: &nbsp; &nbsp; &nbsp; <big> floor( sqrt(X) ) </big>
::* &nbsp; where &nbsp; '''sqrt''' &nbsp;&nbsp; is the &nbsp; square root &nbsp; function for non─negative real numbers, &nbsp; and
::* &nbsp; where &nbsp; '''floor''' &nbsp; is the &nbsp; floor &nbsp; function for real numbers.
If the hardware supports the computation of (real) square roots, &nbsp; the above method might be a faster method for
small numbers that don't have very many significant (decimal) digits.
However, floating point arithmetic is limited in the number of &nbsp; (binary or decimal) &nbsp; digits that it can support.
;Pseudo─code using quadratic residue:
For this task, the integer square root of a non─negative number will be computed using a version
of &nbsp; ''quadratic residue'', &nbsp; which has the advantage that no &nbsp; ''floating point'' &nbsp; calculations are
used, &nbsp; only integer arithmetic.
Furthermore, the two divisions can be performed by bit shifting, &nbsp; and the one multiplication can also be be performed by bit shifting or additions.
The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.
Pseudo─code of a procedure for finding the integer square root of &nbsp; '''X''' &nbsp; &nbsp; &nbsp; (all variables are integers):
q ◄── 1 /*initialize Q to unity. */
/*find a power of 4 that's greater than X.*/
perform while q <= x /*perform while Q <= X. */
q ◄── q * 4 /*multiply Q by four. */
end /*perform*/
/*Q is now greater than X.*/
z ◄── x /*set Z to the value of X.*/
r ◄── 0 /*initialize R to zero. */
perform while q > 1 /*perform while Q > unity. */
q ◄── q ÷ 4 /*integer divide by four. */
t ◄── z - r - q /*compute value of T. */
r ◄── r ÷ 2 /*integer divide by two. */
if t >= 0 then do
z ◄── t /*set Z to value of T. */
r ◄── r + q /*compute new value of R. */
end
end /*perform*/
/*R is now the Isqrt(X). */
/* Sidenote: Also, Z is now the remainder after square root (i.e. */
/* R^2 + Z = X, so if Z = 0 then X is a perfect square). */
Another version for the (above) &nbsp; 1<sup>st</sup> &nbsp; '''perform''' &nbsp; is:
perform until q > X /*perform until Q > X. */
q ◄── q * 4 /*multiply Q by four. */
end /*perform*/
Integer square roots of some values:
Isqrt( 0) <small>is</small> 0 Isqrt(60) <small>is</small> 7 Isqrt( 99) <small>is</small> 9
Isqrt( 1) <small>is</small> 1 Isqrt(61) <small>is</small> 7 Isqrt(100) <small>is</small> 10
Isqrt( 2) <small>is</small> 1 Isqrt(62) <small>is</small> 7 Isqrt(102) <small>is</small> 10
Isqrt( 3) <small>is</small> 1 Isqrt(63) <small>is</small> 7
Isqrt( 4) <small>is</small> 2 Isqrt(64) <small>is</small> 8 Isqet(120) <small>is</small> 10
Isqrt( 5) <small>is</small> 2 Isqrt(65) <small>is</small> 8 Isqrt(121) <small>is</small> 11
Isqrt( 6) <small>is</small> 2 Isqrt(66) <small>is</small> 8 Isqrt(122) <small>is</small> 11
Isqrt( 7) <small>is</small> 2 Isqrt(67) <small>is</small> 8
Isqrt( 8) <small>is</small> 2 Isqrt(68) <small>is</small> 8 Isqrt(143) <small>is</small> 11
Isqrt( 9) <small>is</small> 3 Isqrt(69) <small>is</small> 8 Isqrt(144) <small>is</small> 12
Isqrt(10) <small>is</small> 3 Isqrt(70) <small>is</small> 8 Isqrt(145) <small>is</small> 12
;Task:
Compute and show all output here &nbsp; (on this page) &nbsp; for:
::* &nbsp; the <code>Isqrt</code> of the &nbsp; &nbsp; integers &nbsp; &nbsp; from &nbsp; &nbsp; '''0''' ───► '''65''' &nbsp;&nbsp; (inclusive), shown in a horizontal format.
::* &nbsp; the <code>Isqrt</code> of the &nbsp; odd powers&nbsp; from &nbsp; '''7<sup>1</sup>''' ───► '''7<sup>73''' &nbsp; (inclusive), shown in a &nbsp; vertical &nbsp; format.
::* &nbsp; use commas in the displaying of larger numbers.
You can show more numbers for the 2<sup>nd</sup> requirement if the displays fits on one screen on Rosetta Code.
<br>If your computer programming language only supports smaller integers, &nbsp; show what you can.
;Related tasks:
:* &nbsp; [[Sequence_of_non-squares|sequence of non-squares]]
:* &nbsp; [[Integer_roots|integer roots]]
:* &nbsp; [[Square_Root_by_Hand|square root by hand]]
<br><br>

View file

@ -0,0 +1,41 @@
F commatize(number, step = 3, sep = ,)
V s = reversed(String(number))
String r = s[0]
L(i) 1 .< s.len
I i % step == 0
r = sep
r = s[i]
R reversed(r)
F isqrt(BigInt x)
assert(x >= 0)
V q = BigInt(1)
L q <= x
q *= 4
V z = x
V r = BigInt(0)
L q > 1
q I/= 4
V t = z - r - q
r I/= 2
I t >= 0
z = t
r += q
R r
print(The integer square root of integers from 0 to 65 are:)
L(i) 66
print(isqrt(BigInt(i)), end' )
print()
print(The integer square roots of powers of 7 from 7^1 up to 7^73 are:)
print(power 7 ^ power integer square root)
print(----- --------------------------------------------------------------------------------- -----------------------------------------)
V pow7 = BigInt(7)
V bi49 = BigInt(49)
L(i) (1..73).step(2)
print(#2 #84 #41.format(i, commatize(pow7), commatize(isqrt(pow7))))
pow7 *= bi49

View file

@ -0,0 +1,66 @@
BEGIN # Integer square roots #
PR precision 200 PR
# returns the integer square root of x; x must be >= 0 #
PROC isqrt = ( LONG LONG INT x )LONG LONG INT:
IF x < 0 THEN print( ( "Negative number in isqrt", newline ) );stop
ELIF x < 2 THEN x
ELSE
# x is greater than 1 #
# find a power of 4 that's greater than x #
LONG LONG INT q := 1;
WHILE q <= x DO q *:= 4 OD;
# find the root #
LONG LONG INT z := x;
LONG LONG INT r := 0;
WHILE q > 1 DO
q OVERAB 4;
LONG LONG INT t = z - r - q;
r OVERAB 2;
IF t >= 0 THEN
z := t;
r +:= q
FI
OD;
r
FI; # isqrt #
# returns a string representation of n with commas #
PROC commatise = ( LONG LONG INT n )STRING:
BEGIN
STRING result := "";
STRING unformatted = whole( n, 0 );
INT ch count := 0;
FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO
IF ch count <= 2 THEN ch count +:= 1
ELSE ch count := 1; "," +=: result
FI;
unformatted[ c ] +=: result
OD;
result
END; # commatise #
# left-pads a string to at least n characters #
PROC pad left = ( STRING s, INT n )STRING:
BEGIN
STRING result := s;
WHILE ( UPB result - LWB result ) + 1 < n DO " " +=: result OD;
result
END; # pad left #
# task test cases #
print( ( "Integer square roots of 0..65", newline ) );
FOR i FROM 0 TO 65 DO print( ( " ", whole( isqrt( i ), 0 ) ) ) OD;
print( ( newline ) );
# integer square roots of odd powers of 7 #
print( ( "Integer square roots of 7^n", newline ) );
print( ( " n|", pad left( "7^n", 82 ), "|", pad left( "isqrt(7^n)", 42 ), newline ) );
LONG LONG INT p7 := 7;
FOR p BY 2 TO 73 DO
print( ( whole( p, -2 )
, "|"
, pad left( commatise( p7 ), 82 )
, "|"
, pad left( commatise( isqrt( p7 ) ), 42 )
, newline
)
);
p7 *:= 49
OD
END

View file

@ -0,0 +1,59 @@
BEGIN
COMMENT
RETURN INTEGER SQUARE ROOT OF N USING QUADRATIC RESIDUE
ALGORITHM. WARNING: THE FUNCTION WILL FAIL FOR X GREATER
THAN 4095;
INTEGER FUNCTION ISQRT(X);
INTEGER X;
BEGIN
INTEGER Q, R, Z, T;
Q := 1;
WHILE Q <= X DO
Q := Q * 4; % WARNING! OVERFLOW YIELDS 0 %
Z := X;
R := 0;
WHILE Q > 1 DO
BEGIN
Q := Q / 4;
T := Z - R - Q;
R := R / 2;
IF T >= 0 THEN
BEGIN
Z := T;
R := R + Q;
END;
END;
ISQRT := R;
END;
COMMENT - LET'S EXERCISE THE FUNCTION;
INTEGER I, COL;
WRITE("INTEGER SQUARE ROOT OF FIRST 65 NUMBERS:");
WRITE("");
COL := 1;
FOR I := 1 STEP 1 UNTIL 65 DO
BEGIN
WRITEON(ISQRT(I));
COL := COL + 1;
IF COL > 10 THEN
BEGIN
WRITE("");
COL := 1;
END;
END;
WRITE("");
WRITE(" N 7^N ISQRT");
WRITE("--------------------");
COMMENT - ODD POWERS OF 7 GREATER THAN 3 WILL CAUSE OVERFLOW;
FOR I := 1 STEP 2 UNTIL 3 DO
BEGIN
INTEGER POW7;
POW7 := 7**I;
WRITE(I, POW7, ISQRT(POW7));
END;
WRITE("THAT'S ALL. GOODBYE.");
END

View file

@ -0,0 +1,14 @@
% RETURN INTEGER SQUARE ROOT OF N %
INTEGER FUNCTION ISQRT(N);
INTEGER N;
BEGIN
INTEGER R1, R2;
R1 := N;
R2 := 1;
WHILE R1 > R2 DO
BEGIN
R1 := (R1+R2) / 2;
R2 := N / R1;
END;
ISQRT := R1;
END;

View file

@ -0,0 +1,80 @@
begin % Integer square roots by quadratic residue %
% returns the integer square root of x - x must be >= 0 %
integer procedure iSqrt ( integer value x ) ;
if x < 0 then begin assert x >= 0; 0 end
else if x < 2 then x
else begin
% x is greater than 1 %
integer q, r, t, z;
% find a power of 4 that's greater than x %
q := 1;
while q <= x do q := q * 4;
% find the root %
z := x;
r := 0;
while q > 1 do begin
q := q div 4;
t := z - r - q;
r := r div 2;
if t >= 0 then begin
z := t;
r := r + q
end if_t_ge_0
end while_q_gt_1 ;
r
end isqrt;
% writes n in 14 character positions with separator commas %
procedure writeonWithCommas ( integer value n ) ;
begin
string(10) decDigits;
string(14) r;
integer v, cPos, dCount;
decDigits := "0123456789";
v := abs n;
r := " ";
r( 13 // 1 ) := decDigits( v rem 10 // 1 );
v := v div 10;
cPos := 12;
dCount := 1;
while cPos > 0 and v > 0 do begin
r( cPos // 1 ) := decDigits( v rem 10 // 1 );
v := v div 10;
cPos := cPos - 1;
dCount := dCount + 1;
if v not = 0 and dCount = 3 then begin
r( cPos // 1 ) := ",";
cPos := cPos - 1;
dCount := 0
end if_v_ne_0_and_dCount_eq_3
end for_cPos;
r( cPos // 1 ) := if n < 0 then "-" else " ";
writeon( s_w := 0, r )
end writeonWithCommas ;
begin % task test cases %
integer prevI, prevR, root, p7;
write( "Integer square roots of 0..65 (values the same as the previous one not shown):" );
write();
prevR := prevI := -1;
for i := 0 until 65 do begin
root := iSqrt( i );
if root not = prevR then begin
prevR := root;
prevI := i;
writeon( i_w := 1, s_w := 0, " ", i, ":", root )
end
else if prevI = i - 1 then writeon( "..." );
end for_i ;
write();
% integer square roots of odd powers of 7 %
write( "Integer square roots of 7^n, odd n" );
write( " n| 7^n| isqrt(7^n)" );
write( " -+--------------+--------------" );
p7 := 7;
for p := 1 step 2 until 9 do begin
write( i_w := 2, s_w := 0, p );
writeon( s_w := 0, "|" ); writeonWithCommas( p7 );
writeon( s_w := 0, "|" ); writeonWithCommas( iSqrt( p7 ) );
p7 := p7 * 49
end for_p
end task_test_cases
end.

View file

@ -0,0 +1,13 @@
i{x
q(×4){>x}1
{ r z q
qq÷4
t(z-r)-q
rr÷2
zz t[1+t0]
rr+q×t0
r z q
}{ r z q
q1
}0 x q
}

View file

@ -0,0 +1,220 @@
(*
Compile with "myatscc isqrt.dats", thus obtaining an executable called
"isqrt".
##myatsccdef=\
patscc -O2 \
-I"${PATSHOME}/contrib/atscntrb" \
-IATS "${PATSHOME}/contrib/atscntrb" \
-D_GNU_SOURCE -DATS_MEMALLOC_LIBC \
-o $fname($1) $1 -lgmp
*)
#include "share/atspre_staload.hats"
(* An interface to GNU Multiple Precision. The type system will help
ensure that you do "mpz_clear" on whatever you allocate. *)
staload "atscntrb-hx-libgmp/SATS/gmp.sats"
(* As of this writing, gmp.dats is empty, but it does no harm to
staload it. *)
staload _ = "atscntrb-hx-libgmp/DATS/gmp.dats"
fn
find_a_power_of_4_greater_than_x
(x : &mpz, (* Input. *)
q : &mpz? >> mpz) (* Output. *)
: void =
let
fun
loop (x : &mpz, q : &mpz) : void =
if 0 <= mpz_cmp (x, q) then
begin
mpz_mul (q, 4u);
loop (x, q)
end
in
mpz_init_set (q, 1u);
loop (x, q)
end
fn
isqrt_and_remainder
(x : &mpz, (* Input. *)
r : &mpz? >> mpz, (* Output: square root. *)
z : &mpz? >> mpz) (* Output: remainder. *)
: void =
let
fun
loop (q : &mpz, z : &mpz, r : &mpz, t : &mpz) : void =
if 0 < mpz_cmp (q, 1u) then
begin
mpz_tdiv_q (q, 4u);
mpz_set_mpz (t, z);
mpz_sub (t, r);
mpz_sub (t, q);
mpz_tdiv_q (r, 2u);
if 0 <= mpz_cmp (t, 0u) then
begin
mpz_set_mpz (z, t);
mpz_add (r, q);
end;
loop (q, z, r, t);
end
var q : mpz
var t : mpz
in
find_a_power_of_4_greater_than_x (x, q);
mpz_init_set (z, x);
mpz_init_set (r, 0u);
mpz_init (t);
loop (q, z, r, t);
mpz_clear (q);
mpz_clear (t);
end
fn
isqrt (x : &mpz, (* Input. *)
r : &mpz? >> mpz) (* Output: square root. *)
: void =
let
var z : mpz
in
isqrt_and_remainder (x, r, z);
mpz_clear (z);
end
fn
print_n_spaces (n : uint) : void =
let
var i : [i : nat] uint i
in
for (i := 0u; i < n; i := succ i)
print! (" ")
end
fn
print_with_commas (n : &mpz,
num_columns : uint) : void =
let
fun
make_list (q : &mpz,
r : &mpz,
lst : List0_vt char,
i : uint) : List_vt char =
if mpz_cmp (q, 0u) = 0 then
lst
else
let
val _ = mpz_tdiv_qr (q, r, 10u)
val ones_place = mpz_get_int (r)
val digit = int2char0 (ones_place + char2i '0')
in
if i = 3u then
let
val lst = list_vt_cons (',', lst)
val lst = list_vt_cons (digit, lst)
in
make_list (q, r, lst, 1u)
end
else
let
val lst = list_vt_cons (digit, lst)
in
make_list (q, r, lst, succ i)
end
end
var q : mpz
var r : mpz
val _ = mpz_init_set (q, n)
val _ = mpz_init (r)
val char_lst = make_list (q, r, list_vt_nil (), 0u)
val _ = mpz_clear (q)
val _ = mpz_clear (r)
fun
print_and_consume_lst (char_lst : List0_vt char) : void =
case+ char_lst of
| ~ list_vt_nil () => ()
| ~ list_vt_cons (head, tail) =>
begin
print! (head);
print_and_consume_lst (tail);
end
prval _ = lemma_list_vt_param (char_lst)
val len = i2u (list_vt_length (char_lst))
in
assertloc (len <= num_columns);
print_n_spaces (num_columns - len);
print_and_consume_lst (char_lst)
end
fn
do_the_roots_of_0_to_65 () : void =
let
var i : mpz
in
mpz_init_set (i, 0u);
while (mpz_cmp (i, 65u) <= 0)
let
var r : mpz
in
isqrt (i, r);
fprint (stdout_ref, r);
print! (" ");
mpz_add (i, 1u);
mpz_clear (r);
end;
mpz_clear (i);
end
fn
do_the_roots_of_odd_powers_of_7 () : void =
let
var seven : mpz
var seven_raised_i : mpz
var i_mpz : mpz
var i : [i : pos] uint i
in
mpz_init_set (seven, 7u);
mpz_init (seven_raised_i);
mpz_init (i_mpz);
for (i := 1u; i <= 73u; i := succ (succ i))
let
var r : mpz
in
mpz_pow_uint (seven_raised_i, seven, i);
isqrt (seven_raised_i, r);
mpz_set_uint (i_mpz, i);
print_with_commas (i_mpz, 2u);
print! (" ");
print_with_commas (seven_raised_i, 84u);
print! (" ");
print_with_commas (r, 43u);
print! ("\n");
mpz_clear (r);
end;
mpz_clear (seven);
mpz_clear (seven_raised_i);
mpz_clear (i_mpz);
end
implement
main0 () =
begin
print! ("isqrt(i) for 0 <= i <= 65:\n\n");
do_the_roots_of_0_to_65 ();
print! ("\n\n\n");
print! ("isqrt(7**i) for 1 <= i <= 73, i odd:\n\n");
print! (" i 7**i sqrt(7**i)\n");
print! ("-----------------------------------------------------------------------------------------------------------------------------------\n");
do_the_roots_of_odd_powers_of_7 ();
end

View file

@ -0,0 +1,87 @@
with Ada.Text_Io;
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Strings.Fixed;
procedure Integer_Square_Root is
use Ada.Numerics.Big_Numbers.Big_Integers;
use Ada.Text_Io;
function Isqrt (X : Big_Integer) return Big_Integer is
Q : Big_Integer := 1;
Z, T, R : Big_Integer;
begin
while Q <= X loop
Q := Q * 4;
end loop;
Z := X;
R := 0;
while Q > 1 loop
Q := Q / 4;
T := Z - R - Q;
R := R / 2;
if T >= 0 then
Z := T;
R := R + Q;
end if;
end loop;
return R;
end Isqrt;
function Commatize (N : Big_Integer; Width : Positive) return String is
S : constant String := To_String (N, Width);
Image : String (1 .. Width + Width / 3) := (others => ' ');
Pos : Natural := Image'Last;
begin
for I in S'Range loop
Image (Pos) := S (S'Last - I + S'First);
exit when Image (Pos) = ' ';
Pos := Pos - 1;
if I mod 3 = 0 and S (S'Last - I + S'First - 1) /= ' ' then
Image (Pos) := ''';
Pos := Pos - 1;
end if;
end loop;
return Image;
end Commatize;
type Mode_Kind is (Tens, Ones, Spacer, Result);
begin
Put_Line ("Integer square roots of integers 0 .. 65:");
for Mode in Mode_Kind loop
for N in 0 .. 65 loop
case Mode is
when Tens => Put ((if N / 10 = 0
then " "
else Natural'Image (N / 10)));
when Ones => Put (Natural'Image (N mod 10));
when Spacer => Put ("--");
when Result => Put (To_String (Isqrt (To_Big_Integer (N))));
end case;
end loop;
New_Line;
end loop;
New_Line;
declare
package Integer_Io is new Ada.Text_Io.Integer_Io (Natural);
use Ada.Strings.Fixed;
N : Integer := 1;
P, R : Big_Integer;
begin
Put_Line ("| N|" & 80 * " " & "7**N|" & 30 * " " & "isqrt (7**N)|");
Put_Line (133 * "=");
loop
P := 7**N;
R := Isqrt (P);
Put ("|"); Integer_Io.Put (N, Width => 3);
Put ("|"); Put (Commatize (P, Width => 63));
Put ("|"); Put (Commatize (R, Width => 32));
Put ("|"); New_Line;
exit when N >= 73;
N := N + 2;
end loop;
Put_Line (133 * "=");
end;
end Integer_Square_Root;

View file

@ -0,0 +1,55 @@
on isqrt(x)
set q to 1
repeat until (q > x)
set q to q * 4
end repeat
set z to x
set r to 0
repeat while (q > 1)
set q to q div 4
set t to z - r - q
set r to r div 2
if (t > -1) then
set z to t
set r to r + q
end if
end repeat
return r
end isqrt
-- Task code
on intToText(n, separator)
set output to ""
repeat until (n < 1000)
set output to separator & (text 2 thru 4 of ((1000 + (n mod 1000) as integer) as text)) & output
set n to n div 1000
end repeat
return (n as integer as text) & output
end intToText
on doTask()
-- Get the integer and power results.
set {integerResults, powerResults} to {{}, {}}
repeat with x from 0 to 65
set end of integerResults to isqrt(x)
end repeat
repeat with p from 1 to 73 by 2
set x to 7 ^ p
if (x > 1.0E+15) then exit repeat -- Beyond the precision of AppleScript reals.
set end of powerResults to "7^" & p & tab & "(" & intToText(x, ",") & "):" & (tab & tab & intToText(isqrt(x), ","))
end repeat
-- Format and output.
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to space
set output to {"Isqrts of integers from 0 to 65:", space & integerResults, ¬
"Isqrts of odd powers of 7 from 1 to " & (p - 2) & ":", powerResults}
set AppleScript's text item delimiters to linefeed
set output to output as text
set AppleScript's text item delimiters to astid
return output
end doTask
doTask()

View file

@ -0,0 +1,12 @@
"Isqrts of integers from 0 to 65:
0 1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8
Isqrts of odd powers of 7 from 1 to 17:
7^1 (7): 2
7^3 (343): 18
7^5 (16,807): 129
7^7 (823,543): 907
7^9 (40,353,607): 6,352
7^11 (1,977,326,743): 44,467
7^13 (96,889,010,407): 311,269
7^15 (4,747,561,509,943): 2,178,889
7^17 (232,630,513,987,207): 15,252,229"

View file

@ -0,0 +1,26 @@
commatize: function [x][
reverse join.with:"," map split.every: 3 split reverse to :string x => join
]
isqrt: function [x][
num: new x
q: new 1
r: new 0
while [q =< num]-> shl.safe 'q 2
while [q > 1][
shr 'q 2
t: (num-r)-q
shr 'r 1
if t >= 0 [
num: t
r: new r+q
]
]
return r
]
print map 0..65 => isqrt
loop range 1 .step: 2 72 'n ->
print [n "\t" commatize isqrt 7^n]

View file

@ -0,0 +1,31 @@
print "Integer square root of first 65 numbers:"
for n = 1 to 65
print ljust(isqrt(n),3);
next n
print : print
print "Integer square root of odd powers of 7"
print " n 7^n isqrt"
print "-"*36
for n = 1 to 21 step 2
pow7 = int(7 ^ n)
print rjust(n,3);rjust(pow7,20);rjust(isqrt(pow7),12)
next n
end
function isqrt(x)
q = 1
while q <= x
q *= 4
end while
r = 0
while q > 1
q /= 4
t = x - r - q
r /= 2
if t >= 0 then
x = t
r += q
end if
end while
return int(r)
end function

View file

@ -0,0 +1,62 @@
#include <iomanip>
#include <iostream>
#include <sstream>
#include <boost/multiprecision/cpp_int.hpp>
using big_int = boost::multiprecision::cpp_int;
template <typename integer>
integer isqrt(integer x) {
integer q = 1;
while (q <= x)
q <<= 2;
integer r = 0;
while (q > 1) {
q >>= 2;
integer t = x - r - q;
r >>= 1;
if (t >= 0) {
x = t;
r += q;
}
}
return r;
}
std::string commatize(const big_int& n) {
std::ostringstream out;
out << n;
std::string str(out.str());
std::string result;
size_t digits = str.size();
result.reserve(4 * digits/3);
for (size_t i = 0; i < digits; ++i) {
if (i > 0 && i % 3 == digits % 3)
result += ',';
result += str[i];
}
return result;
}
int main() {
std::cout << "Integer square root for numbers 0 to 65:\n";
for (int n = 0; n <= 65; ++n)
std::cout << isqrt(n) << ' ';
std::cout << "\n\n";
std::cout << "Integer square roots of odd powers of 7 from 1 to 73:\n";
const int power_width = 83, isqrt_width = 42;
std::cout << " n |"
<< std::setw(power_width) << "7 ^ n" << " |"
<< std::setw(isqrt_width) << "isqrt(7 ^ n)"
<< '\n';
std::cout << std::string(6 + power_width + isqrt_width, '-') << '\n';
big_int p = 7;
for (int n = 1; n <= 73; n += 2, p *= 49) {
std::cout << std::setw(2) << n << " |"
<< std::setw(power_width) << commatize(p) << " |"
<< std::setw(isqrt_width) << commatize(isqrt(p))
<< '\n';
}
return 0;
}

View file

@ -0,0 +1,26 @@
using System;
using static System.Console;
using BI = System.Numerics.BigInteger;
 
class Program {
 
static BI isqrt(BI x) { BI q = 1, r = 0, t; while (q <= x) q <<= 2; while (q > 1) {
q >>= 2; t = x - r - q; r >>= 1; if (t >= 0) { x = t; r += q; } } return r; }
 
static void Main() { const int max = 73, smax = 65;
int power_width = ((BI.Pow(7, max).ToString().Length / 3) << 2) + 3,
isqrt_width = (power_width + 1) >> 1;
WriteLine("Integer square root for numbers 0 to {0}:", smax);
for (int n = 0; n <= smax; ++n) Write("{0} ",
(n / 10).ToString().Replace("0", " ")); WriteLine();
for (int n = 0; n <= smax; ++n) Write("{0} ", n % 10); WriteLine();
WriteLine(new String('-', (smax << 1) + 1));
for (int n = 0; n <= smax; ++n) Write("{0} ", isqrt(n));
WriteLine("\n\nInteger square roots of odd powers of 7 from 1 to {0}:", max);
string s = string.Format("[0,2] |[1,{0}:n0] |[2,{1}:n0]",
power_width, isqrt_width).Replace("[", "{").Replace("]", "}");
WriteLine(s, "n", "7 ^ n", "isqrt(7 ^ n)");
WriteLine(new String('-', power_width + isqrt_width + 6));
BI p = 7; for (int n = 1; n <= max; n += 2, p *= 49)
WriteLine (s, n, p, isqrt(p)); }
}

View file

@ -0,0 +1,38 @@
#include <stdint.h>
#include <stdio.h>
int64_t isqrt(int64_t x) {
int64_t q = 1, r = 0;
while (q <= x) {
q <<= 2;
}
while (q > 1) {
int64_t t;
q >>= 2;
t = x - r - q;
r >>= 1;
if (t >= 0) {
x = t;
r += q;
}
}
return r;
}
int main() {
int64_t p;
int n;
printf("Integer square root for numbers 0 to 65:\n");
for (n = 0; n <= 65; n++) {
printf("%lld ", isqrt(n));
}
printf("\n\n");
printf("Integer square roots of odd powers of 7 from 1 to 21:\n");
printf(" n | 7 ^ n | isqrt(7 ^ n)\n");
p = 7;
for (n = 1; n <= 21; n += 2, p *= 49) {
printf("%2d | %18lld | %12lld\n", n, p, isqrt(p));
}
}

View file

@ -0,0 +1,68 @@
% This program uses the 'bigint' cluster from PCLU's 'misc.lib'
% Integer square root of a bigint
isqrt = proc (x: bigint) returns (bigint)
% Initialize a couple of bigints we will reuse
own zero: bigint := bigint$i2bi(0)
own one: bigint := bigint$i2bi(1)
own two: bigint := bigint$i2bi(2)
own four: bigint := bigint$i2bi(4)
q: bigint := one
while q <= x do q := q * four end
t: bigint
z: bigint := x
r: bigint := zero
while q>one do
q := q / four
t := z - r - q
r := r / two
if t >= zero then
z := t
r := r + q
end
end
return(r)
end isqrt
% Format a bigint using commas
fmt = proc (x: bigint) returns (string)
own zero: bigint := bigint$i2bi(0)
own ten: bigint := bigint$i2bi(10)
if x=zero then return("0") end
out: array[char] := array[char]$[]
ds: int := 0
while x>zero do
array[char]$addl(out, char$i2c(bigint$bi2i(x // ten) + 48))
x := x / ten
ds := ds + 1
if x~=zero cand ds//3=0 then
array[char]$addl(out, ',')
end
end
return(string$ac2s(out))
end fmt
start_up = proc ()
po: stream := stream$primary_output()
% print square roots from 0..65
stream$putl(po, "isqrt of 0..65:")
for i: int in int$from_to(0, 65) do
stream$puts(po, fmt(isqrt(bigint$i2bi(i))) || " ")
end
% print square roots of odd powers
stream$putl(po, "\n\nisqrt of odd powers of 7:")
seven: bigint := bigint$i2bi(7)
for p: int in int$from_to_by(1, 73, 2) do
stream$puts(po, "isqrt(7^")
stream$putright(po, int$unparse(p), 2)
stream$puts(po, ") = ")
stream$putright(po, fmt(isqrt(seven ** bigint$i2bi(p))), 41)
stream$putl(po, "")
end
end start_up

View file

@ -0,0 +1,74 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. I-SQRT.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 QUAD-RET-VARS.
03 X PIC 9(18).
03 Q PIC 9(18).
03 Z PIC 9(18).
03 T PIC S9(18).
03 R PIC 9(18).
01 TO-65-VARS.
03 ISQRT-N PIC 99.
03 DISP-LN PIC X(22) VALUE SPACES.
03 DISP-FMT PIC Z9.
03 PTR PIC 99 VALUE 1.
01 BIG-SQRT-VARS.
03 POW-7 PIC 9(18) VALUE 7.
03 POW-N PIC 99 VALUE 1.
03 POW-N-OUT PIC Z9.
03 POW-7-OUT PIC Z(10).
PROCEDURE DIVISION.
BEGIN.
PERFORM SQRTS-TO-65.
PERFORM BIG-SQRTS.
STOP RUN.
SQRTS-TO-65.
PERFORM DISP-SMALL-SQRT
VARYING ISQRT-N FROM 0 BY 1
UNTIL ISQRT-N IS GREATER THAN 65.
DISP-SMALL-SQRT.
MOVE ISQRT-N TO X.
PERFORM ISQRT.
MOVE R TO DISP-FMT.
STRING DISP-FMT DELIMITED BY SIZE INTO DISP-LN
WITH POINTER PTR.
IF PTR IS GREATER THAN 22,
DISPLAY DISP-LN,
MOVE 1 TO PTR.
BIG-SQRTS.
PERFORM BIG-SQRT 10 TIMES.
BIG-SQRT.
MOVE POW-7 TO X.
PERFORM ISQRT.
MOVE POW-N TO POW-N-OUT.
MOVE R TO POW-7-OUT.
DISPLAY "ISQRT(7^" POW-N-OUT ") = " POW-7-OUT.
ADD 2 TO POW-N.
MULTIPLY 49 BY POW-7.
ISQRT.
MOVE 1 TO Q.
PERFORM MUL-Q-BY-4 UNTIL Q IS GREATER THAN X.
MOVE X TO Z.
MOVE ZERO TO R.
PERFORM ISQRT-STEP UNTIL Q IS NOT GREATER THAN 1.
MUL-Q-BY-4.
MULTIPLY 4 BY Q.
ISQRT-STEP.
DIVIDE 4 INTO Q.
COMPUTE T = Z - R - Q.
DIVIDE 2 INTO R.
IF T IS NOT LESS THAN ZERO,
MOVE T TO Z,
ADD Q TO R.

View file

@ -0,0 +1,66 @@
#!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#
(progn ;;init forms
(ros:ensure-asdf)
#+quicklisp(ql:quickload '() :silent t)
)
(defpackage :ros.script.isqrt.3860764029
(:use :cl))
(in-package :ros.script.isqrt.3860764029)
;;
;; The Rosetta Code integer square root task, in Common Lisp.
;;
;; I translate the tail recursions of the Scheme as regular loops in
;; Common Lisp, although CL compilers most often can optimize tail
;; recursions of the kind. They are not required to, however.
;;
;; As a result, the CL is actually closer to the task's pseudocode
;; than is the Scheme.
;;
;; (The Scheme, by the way, could have been written much as follows,
;; using "set!" where the CL has "setf", and with other such
;; "linguistic" changes.)
;;
(defun find-a-power-of-4-greater-than-x (x)
(let ((q 1))
(loop until (< x q)
do (setf q (* 4 q)))
q))
(defun isqrt+remainder (x)
(let ((q (find-a-power-of-4-greater-than-x x))
(z x)
(r 0))
(loop until (= q 1)
do (progn (setf q (/ q 4))
(let ((z1 (- z r q)))
(setf r (/ r 2))
(when (<= 0 z1)
(setf z z1)
(setf r (+ r q))))))
(values r z)))
(defun rosetta_code_isqrt (x)
(nth-value 0 (isqrt+remainder x)))
(defun main (&rest argv)
(declare (ignorable argv))
(format t "isqrt(i) for ~D <= i <= ~D:~2%" 0 65)
(loop for i from 0 to 64
do (format t "~D " (isqrt i)))
(format t "~D~3%" (isqrt 65))
(format t "isqrt(7**i) for ~D <= i <= ~D, i odd:~2%" 1 73)
(format t "~2@A ~84@A ~43@A~%" "i" "7**i" "sqrt(7**i)")
(format t "~A~%" (make-string 131 :initial-element #\-))
(loop for i from 1 to 73 by 2
for 7**i = (expt 7 i)
for root = (rosetta_code_isqrt 7**i)
do (format t "~2D ~84:D ~43:D~%" i 7**i root)))
;;; vim: set ft=lisp lisp:

View file

@ -0,0 +1,53 @@
include "cowgol.coh";
# Integer square root
sub isqrt(x: uint32): (x0: uint32) is
x0 := x >> 1;
if x0 == 0 then
x0 := x;
return;
end if;
loop
var x1 := (x0 + x/x0) >> 1;
if x1 >= x0 then
break;
end if;
x0 := x1;
end loop;
end sub;
# Power
sub pow(x: uint32, n: uint8): (r: uint32) is
r := 1;
while n > 0 loop
r := r * x;
n := n - 1;
end loop;
end sub;
# Print integer square roots of 0..65
var n: uint32 := 0;
var col: uint8 := 11;
while n <= 65 loop
print_i32(isqrt(n));
col := col - 1;
if col == 0 then
print_nl();
col := 11;
else
print_char(' ');
end if;
n := n + 1;
end loop;
# Cowgol only supports 32-bit integers out of the box, so only powers of 7
# up to 7^11 are printed
var x: uint8 := 0;
while x <= 11 loop
print("isqrt(7^");
print_i8(x);
print(") = ");
print_i32(isqrt(pow(7, x)));
print_nl();
x := x + 1;
end loop;

View file

@ -0,0 +1,64 @@
alert "integer square root of first 65 numbers:"
for n = 1 to 65
let x = n
gosub isqrt
print r
next n
alert "integer square root of odd powers of 7"
cls
cursor 1, 1
for n = 1 to 21 step 2
let x = 7 ^ n
gosub isqrt
print "isqrt of 7 ^ ", n, " = ", r
next n
end
sub isqrt
let q = 1
do
if q <= x then
let q = q * 4
endif
wait
loop q <= x
let r = 0
do
if q > 1 then
let q = q / 4
let t = x - r - q
let r = r / 2
if t >= 0 then
let x = t
let r = r + q
endif
endif
loop q > 1
let r = int(r)
return

View file

@ -0,0 +1,80 @@
import std.bigint;
import std.conv;
import std.exception;
import std.range;
import std.regex;
import std.stdio;
//Taken from the task http://rosettacode.org/wiki/Commatizing_numbers#D
auto commatize(in char[] txt, in uint start=0, in uint step=3, in string ins=",") @safe
in {
assert(step > 0);
} body {
if (start > txt.length || step > txt.length) {
return txt;
}
// First number may begin with digit or decimal point. Exponents ignored.
enum decFloField = ctRegex!("[0-9]*\\.[0-9]+|[0-9]+");
auto matchDec = matchFirst(txt[start .. $], decFloField);
if (!matchDec) {
return txt;
}
// Within a decimal float field:
// A decimal integer field to commatize is positive and not after a point.
enum decIntField = ctRegex!("(?<=\\.)|[1-9][0-9]*");
// A decimal fractional field is preceded by a point, and is only digits.
enum decFracField = ctRegex!("(?<=\\.)[0-9]+");
return txt[0 .. start] ~ matchDec.pre ~ matchDec.hit
.replace!(m => m.hit.retro.chunks(step).join(ins).retro)(decIntField)
.replace!(m => m.hit.chunks(step).join(ins))(decFracField)
~ matchDec.post;
}
auto commatize(BigInt v) {
return commatize(v.to!string);
}
BigInt sqrt(BigInt x) {
enforce(x >= 0);
auto q = BigInt(1);
while (q <= x) {
q <<= 2;
}
auto z = x;
auto r = BigInt(0);
while (q > 1) {
q >>= 2;
auto t = z;
t -= r;
t -= q;
r >>= 1;
if (t >= 0) {
z = t;
r += q;
}
}
return r;
}
void main() {
writeln("The integer square root of integers from 0 to 65 are:");
foreach (i; 0..66) {
write(sqrt(BigInt(i)), ' ');
}
writeln;
writeln("The integer square roots of powers of 7 from 7^1 up to 7^73 are:");
writeln("power 7 ^ power integer square root");
writeln("----- --------------------------------------------------------------------------------- -----------------------------------------");
auto pow7 = BigInt(7);
immutable bi49 = BigInt(49);
for (int i = 1; i <= 73; i += 2) {
writefln("%2d %84s %41s", i, pow7.commatize, sqrt(pow7).commatize);
pow7 *= bi49;
}
}

View file

@ -0,0 +1,40 @@
/* Integer square root using quadratic residue method */
proc nonrec isqrt(ulong x) ulong:
ulong q, z, r;
long t;
q := 1;
while q <= x do q := q << 2 od;
z := x;
r := 0;
while q > 1 do
q := q >> 2;
t := z - r - q;
r := r >> 1;
if t >= 0 then
z := t;
r := r + q
fi
od;
r
corp
proc nonrec main() void:
byte x;
ulong pow7;
/* print isqrt(0) ... isqrt(65) */
for x from 0 upto 65 do
write(isqrt(x):2);
if x % 11 = 10 then writeln() fi
od;
/* print isqrt(7^0) thru isqrt(7^10) */
pow7 := 1;
for x from 0 upto 10 do
writeln("isqrt(7^", x:2, ") = ", isqrt(pow7):5);
pow7 := pow7 * 7
od
corp

View file

@ -0,0 +1,8 @@
// Find Integer Floor sqrt of a Large Integer. Nigel Galloway: July 17th., 2020
let Isqrt n=let rec fN i g l=match(l>0I,i-g-l) with
(true,e) when e>=0I->fN e (g/2I+l) (l/4I)
|(true,_) ->fN i (g/2I) (l/4I)
|_ ->g
fN n 0I (let rec fG g=if g>n then g/4I else fG (g*4I) in fG 1I)
[0I..65I]|>Seq.iter(Isqrt>>string>>printf "%s "); printfn "\n"
let fN n=7I**n in [1..2..73]|>Seq.iter(fN>>Isqrt>>printfn "%a" (fun n g -> n.Write("{0:#,#}", g)))

View file

@ -0,0 +1,27 @@
USING: formatting io kernel locals math math.functions
math.ranges prettyprint sequences tools.memory.private ;
:: isqrt ( x -- n )
1 :> q!
[ q x > ] [ q 4 * q! ] until
x 0 :> ( z! r! )
[ q 1 > ] [
q 4 /i q!
z r - q - :> t
r -1 shift r!
t 0 >= [
t z!
r q + r!
] when
] while
r ;
"Integer square root for numbers 0 to 65 (inclusive):" print
66 <iota> [ bl ] [ isqrt pprint ] interleave nl nl
: align ( str str str -- ) "%2s%85s%44s\n" printf ;
: show ( n -- ) dup 7 swap ^ dup isqrt [ commas ] tri@ align ;
"x" "7^x" "isqrt(7^x)" align
"-" "---" "----------" align
1 73 2 <range> [ show ] each

View file

@ -0,0 +1,2 @@
1[:>:r:@@:@,\;
]~$\!?={:,2+/n

View file

@ -0,0 +1,41 @@
: d., ( n -- ) \ write double precision int, commatized.
tuck dabs
<# begin 2dup 1.000 d> while # # # [char] , hold repeat #s rot sign #>
type space ;
: ., ( n -- ) \ write integer commatized.
s>d d., ;
: 4* s" 2 lshift" evaluate ; immediate
: 4/ s" 2 rshift" evaluate ; immediate
: isqrt-mod ( n -- z r ) \ n = r^2 + z
1 begin 2dup >= while 4* repeat
0 locals| r q z |
begin q 1 > while
q 4/ to q
z r - q - \ t
r 2/ to r
dup 0>= if
to z
r q + to r
else
drop
then
repeat z r ;
: isqrt isqrt-mod nip ;
: task1
." Integer square roots from 0 to 65:" cr
66 0 do i isqrt . loop cr ;
: task2
." Integer square roots of 7^n" cr
7 11 0 do
i 2* 1+ 2 .r 3 spaces
dup isqrt ., cr
49 *
loop ;
task1 cr task2 bye

View file

@ -0,0 +1,11 @@
: sqrt-rem ( n -- sqrt rem)
>r 0 1 begin dup r@ > 0= while 4 * repeat
begin \ find a power of 4 greater than TORS
dup 1 > \ compute while greater than unity
while
2/ 2/ swap over over + negate r@ + \ integer divide by 4
dup 0< if drop 2/ else r> drop >r 2/ over + then swap
repeat drop r> ( sqrt rem)
;
: isqrt-mod sqrt-rem swap ;

View file

@ -0,0 +1,97 @@
MODULE INTEGER_SQUARE_ROOT
IMPLICIT NONE
CONTAINS
! Convert string representation number to string with comma digit separation
FUNCTION COMMATIZE(NUM) RESULT(OUT_STR)
INTEGER(16), INTENT(IN) :: NUM
INTEGER(16) I
CHARACTER(83) :: TEMP, OUT_STR
WRITE(TEMP, '(I0)') NUM
OUT_STR = ""
DO I=0, LEN_TRIM(TEMP)-1
IF (MOD(I, 3) .EQ. 0 .AND. I .GT. 0 .AND. I .LT. LEN_TRIM(TEMP)) THEN
OUT_STR = "," // TRIM(OUT_STR)
END IF
OUT_STR = TEMP(LEN_TRIM(TEMP)-I:LEN_TRIM(TEMP)-I) // TRIM(OUT_STR)
END DO
END FUNCTION COMMATIZE
! Calculate the integer square root for a given integer
FUNCTION ISQRT(NUM)
INTEGER(16), INTENT(IN) :: NUM
INTEGER(16) :: ISQRT
INTEGER(16) :: Q, Z, R, T
Q = 1
Z = NUM
R = 0
T = 0
DO WHILE (Q .LE. NUM)
Q = Q * 4
END DO
DO WHILE (Q .GT. 1)
Q = Q / 4
T = Z - R - Q
R = R / 2
IF (T .GE. 0) THEN
Z = T
R = R + Q
END IF
END DO
ISQRT = R
END FUNCTION ISQRT
END MODULE INTEGER_SQUARE_ROOT
! Demonstration of integer square root for numbers 0-65 followed by odd powers of 7
! from 1-73. Currently this demo takes significant time for numbers above 43
PROGRAM ISQRT_DEMO
USE INTEGER_SQUARE_ROOT
IMPLICIT NONE
INTEGER(16), PARAMETER :: MIN_NUM_HZ = 0
INTEGER(16), PARAMETER :: MAX_NUM_HZ = 65
INTEGER(16), PARAMETER :: POWER_BASE = 7
INTEGER(16), PARAMETER :: POWER_MIN = 1
INTEGER(16), PARAMETER :: POWER_MAX = 73
INTEGER(16), DIMENSION(MAX_NUM_HZ-MIN_NUM_HZ+1) :: VALUES
CHARACTER(2) :: HEADER_1
CHARACTER(83) :: HEADER_2
CHARACTER(83) :: HEADER_3
INTEGER(16) :: I
HEADER_1 = " n"
HEADER_2 = "7^n"
HEADER_3 = "isqrt(7^n)"
WRITE(*,'(A, I0, A, I0)') "Integer square root for numbers ", MIN_NUM_HZ, " to ", MAX_NUM_HZ
DO I=1, SIZE(VALUES)
VALUES(I) = ISQRT(MIN_NUM_HZ+I)
END DO
WRITE(*,'(100I2)') VALUES
WRITE(*,*) NEW_LINE('A')
WRITE(*,'(A,A,A,A,A)') HEADER_1, " | ", HEADER_2, " | ", HEADER_3
WRITE(*,*) REPEAT("-", 8+83*2)
DO I=POWER_MIN,POWER_MAX, 2
WRITE(*,'(I2, A, A, A, A)') I, " | " // COMMATIZE(7**I), " | ", COMMATIZE(ISQRT(7**I))
END DO
END PROGRAM ISQRT_DEMO

View file

@ -0,0 +1,40 @@
function isqrt( byval x as ulongint ) as ulongint
dim as ulongint q = 1, r
dim as longint t
while q <= x
q = q shl 2
wend
while q > 1
q = q shr 2
t = x - r - q
r = r shr 1
if t >= 0 then
x = t
r += q
end if
wend
return r
end function
function commatize( byval N as string ) as string
dim as string bloat = ""
dim as uinteger c = 0
while N<>""
bloat = right(N,1) + bloat
N = left(N, len(N)-1)
c += 1
if c mod 3 = 0 and N<>"" then bloat = "," + bloat
wend
return bloat
end function
for i as ulongint = 0 to 65
print isqrt(i);" ";
next i
print
dim as string ns
for i as uinteger = 1 to 22 step 2
ns = str(isqrt(7^i))
print i, commatize(ns)
next i

View file

@ -0,0 +1,36 @@
include "NSLog.incl"
local fn IntSqrt( x as SInt64 ) as SInt64
SInt64 q = 1, z = x, r = 0, t
do
q = q * 4
until ( q > x )
while( q > 1 )
q = q / 4 : t = z - r - q : r = r / 2
if ( t > -1 ) then z = t : r = r + q
wend
end fn = r
SInt64 p
NSInteger n
CFNumberRef tempNum
CFStringRef tempStr
NSLog( @"Integer square root for numbers 0 to 65:" )
for n = 0 to 65
NSLog( @"%lld \b", fn IntSqrt( n ) )
next
NSLog( @"\n" )
NSLog( @"Integer square roots of odd powers of 7 from 1 to 21:" )
NSLog( @" n | 7 ^ n | fn IntSqrt(7 ^ n)" )
p = 7
for n = 1 to 21 step 2
tempNum = fn NumberWithLongLong( fn IntSqrt(p) )
tempStr = fn NumberDescriptionWithLocale( tempNum, fn LocaleCurrent )
NSLog( @"%2d | %18lld | %12s", n, p, fn StringUTF8String( tempStr ) )
p = p * 49
next
HandleEvents

View file

@ -0,0 +1,60 @@
package main
import (
"fmt"
"log"
"math/big"
)
var zero = big.NewInt(0)
var one = big.NewInt(1)
func isqrt(x *big.Int) *big.Int {
if x.Cmp(zero) < 0 {
log.Fatal("Argument cannot be negative.")
}
q := big.NewInt(1)
for q.Cmp(x) <= 0 {
q.Lsh(q, 2)
}
z := new(big.Int).Set(x)
r := big.NewInt(0)
for q.Cmp(one) > 0 {
q.Rsh(q, 2)
t := new(big.Int)
t.Add(t, z)
t.Sub(t, r)
t.Sub(t, q)
r.Rsh(r, 1)
if t.Cmp(zero) >= 0 {
z.Set(t)
r.Add(r, q)
}
}
return r
}
func commatize(s string) string {
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
return s
}
func main() {
fmt.Println("The integer square roots of integers from 0 to 65 are:")
for i := int64(0); i <= 65; i++ {
fmt.Printf("%d ", isqrt(big.NewInt(i)))
}
fmt.Println()
fmt.Println("\nThe integer square roots of powers of 7 from 7^1 up to 7^73 are:\n")
fmt.Println("power 7 ^ power integer square root")
fmt.Println("----- --------------------------------------------------------------------------------- -----------------------------------------")
pow7 := big.NewInt(7)
bi49 := big.NewInt(49)
for i := 1; i <= 73; i += 2 {
fmt.Printf("%2d %84s %41s\n", i, commatize(pow7.String()), commatize(isqrt(pow7).String()))
pow7.Mul(pow7, bi49)
}
}

View file

@ -0,0 +1,15 @@
import Data.Bits
isqrt :: Integer -> Integer
isqrt n = go n 0 (q `shiftR` 2)
where
q = head $ dropWhile (< n) $ iterate (`shiftL` 2) 1
go z r 0 = r
go z r q = let t = z - r - q
in if t >= 0
then go t (r `shiftR` 1 + q) (q `shiftR` 2)
else go z (r `shiftR` 1) (q `shiftR` 2)
main = do
print $ isqrt <$> [1..65]
mapM_ print $ zip [1,3..73] (isqrt <$> iterate (49 *) 7)

View file

@ -0,0 +1,58 @@
link numbers # For the "commas" procedure.
link printf
procedure main ()
write ("isqrt(i) for 0 <= i <= 65:")
write ()
roots_of_0_to_65()
write ()
write ()
write ("isqrt(7**i) for 1 <= i <= 73, i odd:")
write ()
printf ("%2s %84s %43s\n", "i", "7**i", "sqrt(7**i)")
write (repl("-", 131))
roots_of_odd_powers_of_7()
end
procedure roots_of_0_to_65 ()
local i
every i := 0 to 64 do writes (isqrt(i), " ")
write (isqrt(65))
end
procedure roots_of_odd_powers_of_7 ()
local i, power_of_7, root
every i := 1 to 73 by 2 do {
power_of_7 := 7^i
root := isqrt(power_of_7)
printf ("%2d %84s %43s\n", i, commas(power_of_7), commas(root))
}
end
procedure isqrt (x)
local q, z, r, t
q := find_a_power_of_4_greater_than_x (x)
z := x
r := 0
while 1 < q do {
q := ishift(q, -2)
t := z - r - q
r := ishift(r, -1)
if 0 <= t then {
z := t
r +:= q
}
}
return r
end
procedure find_a_power_of_4_greater_than_x (x)
local q
q := 1
while q <= x do q := ishift(q, 2)
return q
end

View file

@ -0,0 +1,28 @@
isqrt_float=: <.@:%:
isqrt_newton=: 9&$: :(x:@:<.@:-:@:(] + x:@:<.@:%)^:_&>~&:x:)
align=: (|.~ i.&' ')"1
comma=: (' ' -.~ [: }: [: , [: (|.) _3 (',' ,~ |.)\ |.)@":&>
While=: {{ u^:(0-.@:-:v)^:_ }}
isqrt=: 3 :0&>
y =. x: y
NB. q is a power of 4 that's greater than y. Append 0 0 under binary representation
q =. y (,&0 0x&.:#:@:])While>: 1x
z =. y NB. set z to the value of y.
r =. 0x NB. initialize r to zero.
while. 1 < q do. NB. perform while q > unity.
q =. _2&}.&.:#: q NB. integer divide by 4 (-2 drop under binary representation)
t =. (z - r) - q NB. compute value of t.
r =. }:&.:#: r NB. integer divide by two. (curtail under binary representation)
if. 0 <: t do.
z =. t NB. set z to value of t
r =. r + q NB. compute new value of r
end.
end.
NB. r is now the isqrt(y). (most recent value computed)
NB. Sidenote: Also, Z is now the remainder after square root
NB. ie. r^2 + z = y, so if z = 0 then x is a perfect square
NB. r , z
)

View file

@ -0,0 +1,45 @@
import java.math.BigInteger;
public class Isqrt {
private static BigInteger isqrt(BigInteger x) {
if (x.compareTo(BigInteger.ZERO) < 0) {
throw new IllegalArgumentException("Argument cannot be negative");
}
var q = BigInteger.ONE;
while (q.compareTo(x) <= 0) {
q = q.shiftLeft(2);
}
var z = x;
var r = BigInteger.ZERO;
while (q.compareTo(BigInteger.ONE) > 0) {
q = q.shiftRight(2);
var t = z;
t = t.subtract(r);
t = t.subtract(q);
r = r.shiftRight(1);
if (t.compareTo(BigInteger.ZERO) >= 0) {
z = t;
r = r.add(q);
}
}
return r;
}
public static void main(String[] args) {
System.out.println("The integer square root of integers from 0 to 65 are:");
for (int i = 0; i <= 65; i++) {
System.out.printf("%s ", isqrt(BigInteger.valueOf(i)));
}
System.out.println();
System.out.println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:");
System.out.println("power 7 ^ power integer square root");
System.out.println("----- --------------------------------------------------------------------------------- -----------------------------------------");
var pow7 = BigInteger.valueOf(7);
var bi49 = BigInteger.valueOf(49);
for (int i = 1; i < 74; i += 2) {
System.out.printf("%2d %,84d %,41d\n", i, pow7, isqrt(pow7));
pow7 = pow7.multiply(bi49);
}
}
}

View file

@ -0,0 +1,37 @@
# For gojq
def idivide($j):
. as $i
| ($i % $j) as $mod
| ($i - $mod) / $j ;
# input should be non-negative
def isqrt:
. as $x
| 1 | until(. > $x; . * 4) as $q
| {$q, $x, r: 0}
| until( .q <= 1;
.q |= idivide(4)
| .t = .x - .r - .q
| .r |= idivide(2)
| if .t >= 0
then .x = .t
| .r += .q
else . end).r ;
def power($n):
. as $in
| reduce range(0;$n) as $i (1; . * $in);
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
## The task:
"The integer square roots of integers from 0 to 65 are:",
[range(0;66) | isqrt],
"",
"The integer square roots of odd powers of 7 from 7^1 up to 7^73 are:",
("power" + " "*16 + "7 ^ power" + " "*70 + "integer square root"),
(range( 1;74;2) as $i
| (7 | power($i)) as $p
| "\($i|lpad(2)) \($p|lpad(84)) \($p | isqrt | lpad(43))" )

View file

@ -0,0 +1,32 @@
using Formatting
function integer_sqrt(x)
@assert(x >= 0)
q = one(x)
while q <= x
q <<= 2
end
z, r = x, zero(x)
while q > 1
q >>= 2
t = z - r - q
r >>= 1
if t >= 0
z = t
r += q
end
end
return r
end
println("The integer square roots of integers from 0 to 65 are:")
println(integer_sqrt.(collect(0:65)))
println("\nThe integer square roots of odd powers of 7 from 7^1 up to 7^73 are:\n")
println("power", " "^36, "7 ^ power", " "^60, "integer square root")
println("----- ", "-"^80, " ------------------------------------------")
pow7 = big"7"
for i in 1:2:73
println(lpad(i, 2), lpad(format(pow7^i, commas=true), 84),
lpad(format(integer_sqrt(pow7^i), commas=true), 43))
end

View file

@ -0,0 +1,43 @@
import java.math.BigInteger
fun isqrt(x: BigInteger): BigInteger {
if (x < BigInteger.ZERO) {
throw IllegalArgumentException("Argument cannot be negative")
}
var q = BigInteger.ONE
while (q <= x) {
q = q.shiftLeft(2)
}
var z = x
var r = BigInteger.ZERO
while (q > BigInteger.ONE) {
q = q.shiftRight(2)
var t = z
t -= r
t -= q
r = r.shiftRight(1)
if (t >= BigInteger.ZERO) {
z = t
r += q
}
}
return r
}
fun main() {
println("The integer square root of integers from 0 to 65 are:")
for (i in 0..65) {
print("${isqrt(BigInteger.valueOf(i.toLong()))} ")
}
println()
println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:")
println("power 7 ^ power integer square root")
println("----- --------------------------------------------------------------------------------- -----------------------------------------")
var pow7 = BigInteger.valueOf(7)
val bi49 = BigInteger.valueOf(49)
for (i in (1..73).step(2)) {
println("%2d %,84d %,41d".format(i, pow7, isqrt(pow7)))
pow7 *= bi49
}
}

View file

@ -0,0 +1,35 @@
function isqrt(x)
local q = 1
local r = 0
while q <= x do
q = q << 2
end
while q > 1 do
q = q >> 2
local t = x - r - q
r = r >> 1
if t >= 0 then
x = t
r = r + q
end
end
return r
end
print("Integer square root for numbers 0 to 65:")
for n=0,65 do
io.write(isqrt(n) .. ' ')
end
print()
print()
print("Integer square roots of oddd powers of 7 from 1 to 21:")
print(" n | 7 ^ n | isqrt(7 ^ n)")
local p = 7
local n = 1
while n <= 21 do
print(string.format("%2d | %18d | %12d", n, p, isqrt(p)))
----------------------
n = n + 2
p = p * 49
end

View file

@ -0,0 +1,64 @@
module integer_square_root (f=-2) {
function IntSqrt(x as long long) {
long long q=1, z=x, t, r
do q*=4&& : until (q>x)
while q>1&&
q|div 4&&:t=z-r-q:r|div 2&&
if t>-1&& then z=t:r+= q
end while
=r
}
long i
print #f, "The integer square root of integers from 0 to 65 are:"
for i=0 to 65
print #f, IntSqrt(i)+" ";
next
print #f
print #f, "Using Long Long Type"
print #f, "The integer square roots of powers of 7 from 7^1 up to 7^21 are:"
for i=1 to 21 step 2 {
print #f, "IntSqrt(7^"+i+")="+(IntSqrt(7&&^i))+" of 7^"+i+" ("+(7&&^I)+")"
}
print #f
function IntSqrt(x as decimal) {
decimal q=1, z=x, t, r
do q*=4 : until (q>x)
while q>1
q/=4:t=z-r-q:r/=2
if t>-1 then z=t:r+= q
end while
=r
}
print #f, "Using Decimal Type"
print #f, "The integer square roots of powers of 7 from 7^23 up to 7^33 are:"
decimal j,p
for i=23 to 33 step 2 {
p=1:for j=1 to i:p*=7@:next
print #f, "IntSqrt(7^"+i+")="+(IntSqrt(p))+" of 7^"+i+" ("+p+")"
}
print #f
function IntSqrt(x as double) {
double q=1, z=x, t, r
do q*=4 : until (q>x)
while q>1
q/=4:t=z-r-q:r/=2
if t>-1 then z=t:r+= q
end while
=r
}
print #f, "Using Double Type"
print #f, "The integer square roots of powers of 7 from 7^19 up to 7^35 are:"
for i=19 to 35 step 2 {
print #f, "IntSqrt(7^"+i+")="+(IntSqrt(7^i))+" of 7^"+i+" ("+(7^i)+")"
}
print #f
}
open "" for output as #f // f = -2 now, direct output to screen
integer_square_root
close #f
open "out.txt" for output as #f
integer_square_root f
close #f
win "notepad", dir$+"out.txt"

View file

@ -0,0 +1,44 @@
NORMAL MODE IS INTEGER
R INTEGER SQUARE ROOT OF X
INTERNAL FUNCTION(X)
ENTRY TO ISQRT.
Q = 1
FNDPW4 WHENEVER Q.LE.X
Q = Q * 4
TRANSFER TO FNDPW4
END OF CONDITIONAL
Z = X
R = 0
FNDRT WHENEVER Q.G.1
Q = Q / 4
T = Z - R - Q
R = R / 2
WHENEVER T.GE.0
Z = T
R = R + Q
END OF CONDITIONAL
TRANSFER TO FNDRT
END OF CONDITIONAL
FUNCTION RETURN R
END OF FUNCTION
R PRINT INTEGER SQUARE ROOTS OF 0..65
THROUGH SQ65, FOR N=0, 11, N.G.65
SQ65 PRINT FORMAT N11, ISQRT.(N), ISQRT.(N+1), ISQRT.(N+2),
0 ISQRT.(N+3), ISQRT.(N+4), ISQRT.(N+5), ISQRT.(N+6),
1 ISQRT.(N+7), ISQRT.(N+8), ISQRT.(N+9), ISQRT.(N+10)
VECTOR VALUES N11 = $11(I1,S1)*$
R MACHINE WORD SIZE ON IBM 704 IS 36 BITS
R PRINT UP TO AND INCLUDING ISQRT(7^12)
POW7 = 1
THROUGH SQ7P12, FOR I=0, 1, I.G.12
PRINT FORMAT SQ7, I, ISQRT.(POW7)
SQ7P12 POW7 = POW7 * 7
VECTOR VALUES SQ7 = $9HISQRT.(7^,I2,4H) = ,I6*$
END OF PROGRAM

View file

@ -0,0 +1,20 @@
ClearAll[ISqrt]
ISqrt[x_Integer?NonNegative] := Module[{q = 1, z, r, t},
While[q <= x,
q *= 4
];
z = x;
r = 0;
While[q > 1,
q = Quotient[q, 4];
t = z - r - q;
r /= 2;
If[t >= 0,
z = t;
r += q
];
];
r
]
ISqrt /@ Range[65]
Column[ISqrt /@ (7^Range[1, 73])]

View file

@ -0,0 +1,48 @@
/* -*- Maxima -*- */
/*
The Rosetta Code integer square root task, in Maxima.
I have not tried to make the output conform quite to the task
description, because Maxima is not a general purpose programming
language. Perhaps someone else will care to do it.
I *do* check that the Rosetta Code routine gives the same results as
the built-in function.
*/
/* pow4gtx -- find a power of 4 greater than x. */
pow4gtx (x) := block (
[q],
q : 1, while q <= x do q : bit_lsh (q, 2),
q
) $
/* rosetta_code_isqrt -- find the integer square root. */
rosetta_code_isqrt (x) := block (
[q, z, r, t],
q : pow4gtx (x),
z : x,
r : 0,
while 1 < q do (
q : bit_rsh (q, 2),
t : z - r - q,
r : bit_rsh (r, 1),
if 0 <= t then (
z : t,
r : r + q
)
),
r
) $
for i : 0 thru 65 do (
display (rosetta_code_isqrt (i),
is (equal (rosetta_code_isqrt (i), isqrt (i))))
) $
for i : 1 thru 73 step 2 do (
display (7**i, rosetta_code_isqrt (7**i),
is (equal (rosetta_code_isqrt (7**i), isqrt (7**i))))
) $

View file

@ -0,0 +1,119 @@
:- module isqrt_in_mercury.
:- interface.
:- import_module io.
:- pred main(io, io).
:- mode main(di, uo) is det.
:- implementation.
:- import_module char.
:- import_module exception.
:- import_module int.
:- import_module integer. % Integers of arbitrary size.
:- import_module list.
:- import_module string.
:- func four = integer.
four = integer(4).
:- func seven = integer.
seven = integer(7).
%% Find a power of 4 greater than X.
:- func pow4gtx(integer) = integer.
pow4gtx(X) = Q :- pow4gtx_(X, one, Q).
%% The tail recursion for pow4gtx.
:- pred pow4gtx_(integer, integer, integer).
:- mode pow4gtx_(in, in, out) is det.
pow4gtx_(X, A, Q) :- if (X < A) then (Q = A)
else (A1 = A * four,
pow4gtx_(X, A1, Q)).
%% Integer square root function.
:- func isqrt(integer) = integer.
isqrt(X) = Root :- isqrt(X, Root, _).
%% Integer square root and remainder.
:- pred isqrt(integer, integer, integer).
:- mode isqrt(in, out, out) is det.
isqrt(X, Root, Remainder) :-
Q = pow4gtx(X),
isqrt_(X, Q, zero, X, Root, Remainder).
%% The tail recursion for isqrt.
:- pred isqrt_(integer, integer, integer, integer, integer, integer).
:- mode isqrt_(in, in, in, in, out, out) is det.
isqrt_(X, Q, R0, Z0, R, Z) :-
if (X < zero) then throw("isqrt of a negative integer")
else if (Q = one) then (R = R0, Z = Z0)
else (Q1 = Q // four,
T = Z0 - R0 - Q1,
(if (T >= zero)
then (R1 = (R0 // two) + Q1,
isqrt_(X, Q1, R1, T, R, Z))
else (R1 is R0 // two,
isqrt_(X, Q1, R1, Z0, R, Z)))).
%% Insert a character, every three digits, into (what presumably is)
%% an integer numeral. (The name "commas" is not very good.)
:- func commas(string, char) = string.
commas(S, Comma) = T :-
RCL = to_rev_char_list(S),
commas_(RCL, Comma, 0, [], CL),
T = from_char_list(CL).
%% The tail recursion for commas.
:- pred commas_(list(char), char, int, list(char), list(char)).
:- mode commas_(in, in, in, in, out) is det.
commas_([], _, _, L, CL) :- L = CL.
commas_([C | Tail], Comma, I, L, CL) :-
if (I = 3) then commas_([C | Tail], Comma, 0, [Comma | L], CL)
else (I1 = I + 1,
commas_(Tail, Comma, I1, [C | L], CL)).
:- pred roots_m_to_n(integer, integer, io, io).
:- mode roots_m_to_n(in, in, di, uo) is det.
roots_m_to_n(M, N, !IO) :-
if (N < M) then true
else (write_string(to_string(isqrt(M)), !IO),
(if (M \= N) then write_string(" ", !IO)
else true),
M1 = M + one,
roots_m_to_n(M1, N, !IO)).
:- pred roots_of_odd_powers_of_7(integer, integer, io, io).
:- mode roots_of_odd_powers_of_7(in, in, di, uo) is det.
roots_of_odd_powers_of_7(M, N, !IO) :-
if (N < M) then true
else (Pow7 = pow(seven, M),
Isqrt = isqrt(Pow7),
format("%2s %84s %43s",
[s(commas(to_string(M), (','))),
s(commas(to_string(Pow7), (','))),
s(commas(to_string(Isqrt), (',')))],
!IO),
nl(!IO),
M1 = M + two,
roots_of_odd_powers_of_7(M1, N, !IO)).
main(!IO) :-
write_string("isqrt(i) for 0 <= i <= 65:", !IO),
nl(!IO), nl(!IO),
roots_m_to_n(zero, integer(65), !IO),
nl(!IO), nl(!IO), nl(!IO),
write_string("isqrt(7**i) for 1 <= i <= 73, i odd:", !IO),
nl(!IO), nl(!IO),
format("%2s %84s %43s", [s("i"), s("7**i"), s("isqrt(7**i)")], !IO),
nl(!IO),
write_string(duplicate_char(('-'), 131), !IO),
nl(!IO),
roots_of_odd_powers_of_7(one, integer(73), !IO).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Instructions for GNU Emacs--
%%% local variables:
%%% mode: mercury
%%% prolog-indent-width: 2
%%% end:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

View file

@ -0,0 +1,63 @@
MODULE IntSqrt;
IMPORT IO;
(* Procedure to find integer square root of a 32-bit unsigned integer. *)
PROCEDURE Isqrt( X : LONGCARD) : LONGCARD;
VAR
Xdiv4, q, r, s, z : LONGCARD;
BEGIN
Xdiv4 := X DIV 4;
q := 1;
WHILE q <= Xdiv4 DO q := 4*q; END;
z := X;
r := 0;
REPEAT
s := q + r;
r := r DIV 2;
IF z >= s THEN
DEC(z, s);
INC(r, q);
END;
q := q DIV 4;
UNTIL q = 0;
RETURN r;
END Isqrt;
(* Main program *)
CONST (* constants for Part 1 of the task *)
Max_n = 65;
NrPerLine = 22;
VAR
n : LONGCARD;
arr_n, arr_i : ARRAY[0..NrPerLine - 1] OF LONGCARD; (* for display *)
j, k : INTEGER;
BEGIN
(* Part 1 *)
k := 0; (* index into arrays *)
FOR n := 0 TO Max_n DO
arr_n[k] := n;
arr_i[k] := Isqrt(n);
INC(k);
IF (k = NrPerLine) OR (n = Max_n) THEN
IO.WrStr( 'Number: ');
FOR j := 0 TO k - 1 DO IO.WrLngCard(arr_n[j], 3); END;
IO.WrLn();
IO.WrStr( 'Isqrt: ');
FOR j := 0 TO k - 1 DO IO.WrLngCard(arr_i[j], 3); END;
IO.WrLn();
k := 0;
END;
END;
IO.WrLn();
(* Part 2 *)
IO.WrStr( 'Isqrt of odd powers of 7'); IO.WrLn();
n := 7;
FOR k := 1 TO 11 BY 2 DO
IF k > 1 THEN n := n*49; END;
IO.WrInt( k, 2); IO.WrStr( ' --> ');
IO.WrLngCard( n, 10); IO.WrStr(' --> ');
IO.WrLngCard( Isqrt(n), 5); IO.WrLn();
END;
END IntSqrt.

View file

@ -0,0 +1,43 @@
import strformat, strutils
import bignum
func isqrt*[T: SomeSignedInt | Int](x: T): T =
## Compute integer square root for signed integers
## and for big integers.
when T is Int:
result = newInt()
var q = newInt(1)
else:
result = 0
var q = T(1)
while q <= x:
q = q shl 2
var z = x
while q > 1:
q = q shr 2
let t = z - result - q
result = result shr 1
if t >= 0:
z = t
result += q
when isMainModule:
echo "Integer square root for numbers 0 to 65:"
for n in 0..65:
stdout.write ' ', isqrt(n)
echo "\n"
echo "Integer square roots of odd powers of 7 from 7^1 to 7^73:"
echo " n" & repeat(' ', 82) & "7^n" & repeat(' ', 34) & "isqrt(7^n)"
echo repeat("", 131)
var x = newInt(7)
for n in countup(1, 73, 2):
echo &"{n:>2} {insertSep($x, ','):>82} {insertSep($isqrt(x), ','):>41}"
x *= 49

View file

@ -0,0 +1,68 @@
(* The Rosetta Code integer square root task, in OCaml, using Zarith
for large integers.
Compile with, for example:
ocamlfind ocamlc -package zarith -linkpkg -o isqrt isqrt.ml
Translated from the Scheme. *)
let find_a_power_of_4_greater_than_x x =
let open Z in
let rec loop q =
if x < q then q else loop (q lsl 2)
in
loop one
let isqrt x =
let open Z in
let rec loop q z r =
if q = one then
r
else
let q = q asr 2 in
let t = z - r - q in
let r = r asr 1 in
if t < zero then
loop q z r
else
loop q t (r + q)
in
let q0 = find_a_power_of_4_greater_than_x x in
let z0 = x in
let r0 = zero in
loop q0 z0 r0
let insert_separators s sep =
let rec loop revchars i newchars =
match revchars with
| [] -> newchars
| revchars when i = 3 -> loop revchars 0 (sep :: newchars)
| c :: tail -> loop tail (i + 1) (c :: newchars)
in
let revchars = List.rev (List.of_seq (String.to_seq s)) in
String.of_seq (List.to_seq (loop revchars 0 []))
let commas s = insert_separators s ','
let main () =
Printf.printf "isqrt(i) for 0 <= i <= 65:\n\n";
for i = 0 to 64 do
Printf.printf "%s " Z.(to_string (isqrt (of_int i)))
done;
Printf.printf "%s\n" Z.(to_string (isqrt (of_int 65)));
Printf.printf "\n\n";
Printf.printf "isqrt(7**i) for 1 <= i <= 73, i odd:\n\n";
Printf.printf "%2s %84s %43s\n" "i" "7**i" "isqrt(7**i)";
for i = 1 to 131 do Printf.printf "-" done;
Printf.printf "\n";
for j = 0 to 36 do
let i = j + j + 1 in
let power = Z.(of_int 7 ** i) in
let root = isqrt power in
Printf.printf "%2d %84s %43s\n"
i (commas (Z.to_string power)) (commas (Z.to_string root))
done
;;
main ()

View file

@ -0,0 +1,61 @@
# -*- ObjectIcon -*-
import io
import ipl.numbers # For the "commas" procedure.
import ipl.printf
procedure main ()
write ("isqrt(i) for 0 <= i <= 65:")
write ()
roots_of_0_to_65()
write ()
write ()
write ("isqrt(7**i) for 1 <= i <= 73, i odd:")
write ()
printf ("%2s %84s %43s\n", "i", "7**i", "sqrt(7**i)")
write (repl("-", 131))
roots_of_odd_powers_of_7()
end
procedure roots_of_0_to_65 ()
local i
every i := 0 to 64 do writes (isqrt(i), " ")
write (isqrt(65))
end
procedure roots_of_odd_powers_of_7 ()
local i, power_of_7, root
every i := 1 to 73 by 2 do {
power_of_7 := 7^i
root := isqrt(power_of_7)
printf ("%2d %84s %43s\n", i, commas(power_of_7), commas(root))
}
end
procedure isqrt (x)
local q, z, r, t
q := find_a_power_of_4_greater_than_x (x)
z := x
r := 0
while 1 < q do {
q := ishift(q, -2)
t := z - r - q
r := ishift(r, -1)
if 0 <= t then {
z := t
r +:= q
}
}
return r
end
procedure find_a_power_of_4_greater_than_x (x)
local q
q := 1
while q <= x do q := ishift(q, 2)
return q
end

View file

@ -0,0 +1,14 @@
(print "Integer square roots of 0..65")
(for-each (lambda (x)
(display (isqrt x))
(display " "))
(iota 66))
(print)
(print "Integer square roots of 7^n")
(for-each (lambda (x)
(print "x: " x ", isqrt: " (isqrt x)))
(map (lambda (i)
(expt 7 i))
(iota 73 1)))
(print)

View file

@ -0,0 +1,96 @@
//************************************************//
// //
// Thanks for rvelthuis for BigIntegers library //
// https://github.com/rvelthuis/DelphiBigNumbers //
// //
//************************************************//
program IsqrtTask;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
Velthuis.BigIntegers;
function isqrt(x: BigInteger): BigInteger;
var
q, r, t: BigInteger;
begin
q := 1;
r := 0;
while (q <= x) do
q := q shl 2;
while (q > 1) do
begin
q := q shr 2;
t := x - r - q;
r := r shr 1;
if (t >= 0) then
begin
x := t;
r := r + q;
end;
end;
Result := r;
end;
function commatize(const n: BigInteger; size: Integer): string;
var
str: string;
digits: Integer;
i: Integer;
begin
Result := '';
str := n.ToString;
digits := str.Length;
for i := 1 to digits do
begin
if ((i > 1) and (((i - 1) mod 3) = (digits mod 3))) then
Result := Result + ',';
Result := Result + str[i];
end;
if Result.Length < size then
Result := string.Create(' ', size - Result.Length) + Result;
end;
const
POWER_WIDTH = 83;
ISQRT_WIDTH = 42;
var
n, i: Integer;
f: TextFile;
p: BigInteger;
begin
AssignFile(f, 'output.txt');
rewrite(f);
Writeln(f, 'Integer square root for numbers 0 to 65:');
for n := 0 to 65 do
Write(f, isqrt(n).ToString, ' ');
Writeln(f, #10#10'Integer square roots of odd powers of 7 from 1 to 73:');
Write(f, ' n |', string.Create(' ', 78), '7 ^ n |', string.Create(' ', 30),
'isqrt(7 ^ n)'#10);
Writeln(f, string.Create('-', 17 + POWER_WIDTH + ISQRT_WIDTH));
p := 7;
n := 1;
repeat
Writeln(f, Format('%2d', [n]), ' |', commatize(p, power_width), ' |',
commatize(isqrt(p), isqrt_width));
inc(n, 2);
p := p * 49;
until (n > 73);
CloseFile(f);
end.

View file

@ -0,0 +1,43 @@
# 20201029 added Perl programming solution
use strict;
use warnings;
use bigint;
use CLDR::Number 'decimal_formatter';
sub integer_sqrt {
( my $x = $_[0] ) >= 0 or die;
my $q = 1;
while ($q <= $x) {
$q <<= 2
}
my ($z, $r) = ($x, 0);
while ($q > 1) {
$q >>= 2;
my $t = $z - $r - $q;
$r >>= 1;
if ($t >= 0) {
$z = $t;
$r += $q;
}
}
return $r
}
print "The integer square roots of integers from 0 to 65 are:\n";
print map { ( integer_sqrt $_ ) . ' ' } (0..65);
my $cldr = CLDR::Number->new();
my $decf = $cldr->decimal_formatter;
print "\nThe integer square roots of odd powers of 7 from 7^1 up to 7^73 are:\n";
print "power", " "x36, "7 ^ power", " "x60, "integer square root\n";
print "----- ", "-"x79, " ------------------------------------------\n";
for (my $i = 1; $i < 74; $i += 2) {
printf("%2s ", $i);
printf("%82s", $decf->format( 7**$i ) );
printf("%44s", $decf->format( integer_sqrt(7**$i) ) ) ;
print "\n";
}

View file

@ -0,0 +1,46 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">isqrt</span><span style="color: #0000FF;">(</span><span style="color: #004080;">mpz</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Argument cannot be negative."</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(),</span>
<span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">mpz_cmp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)<=</span> <span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_fdiv_q_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">q</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">q</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_fdiv_q_ui</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">>=</span> <span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">mpz_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">mpz_add</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">q</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">star</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"*"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">))&</span><span style="color: #000000;">star</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The integer square roots of integers from 0 to 65 are:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">65</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s "</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #000000;">isqrt</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n\npower 7 ^ power integer square root\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"----- --------------------------------------------------------- ----------------------------------------------------------\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">pow7</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">7</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">9000</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">73</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;"><</span><span style="color: #000000;">100</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">or</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;"><</span><span style="color: #000000;">1000</span> <span style="color: #008080;">and</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">or</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%4d %58s %61s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pow7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">isqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pow7</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">mpz_mul_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pow7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pow7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--

View file

@ -0,0 +1,61 @@
%%% -*- Prolog -*-
%%%
%%% The Rosetta Code integer square root task, for SWI Prolog.
%%%
%% pow4gtx/2 -- Find a power of 4 greater than X.
pow4gtx(X, Q) :- pow4gtx(X, 1, Q), !.
pow4gtx(X, A, Q) :- X < A, Q is A.
pow4gtx(X, A, Q) :- A1 is A * 4,
pow4gtx(X, A1, Q).
%% isqrt/2 -- Find integer square root.
%% isqrt/3 -- Find integer square root and remainder.
isqrt(X, R) :- isqrt(X, R, _).
isqrt(X, R, Z) :- pow4gtx(X, Q),
isqrt(X, Q, 0, X, R, Z).
isqrt(_, 1, R0, Z0, R, Z) :- R is R0,
Z is Z0.
isqrt(X, Q, R0, Z0, R, Z) :- Q1 is Q // 4,
T is Z0 - R0 - Q1,
(T >= 0
-> R1 is (R0 // 2) + Q1,
isqrt(X, Q1, R1, T, R, Z)
; R1 is R0 // 2,
isqrt(X, Q1, R1, Z0, R, Z)).
roots(N) :- roots(0, N).
roots(I, N) :- isqrt(I, R),
write(R),
(I =:= N; write(" ")),
I1 is I + 1,
(N < I1, !; roots(I1, N)).
rootspow7(N) :- rootspow7(1, N).
rootspow7(I, N) :- Pow7 is 7**I,
isqrt(Pow7, R),
format("~t~D~2|~t~D~87|~t~D~131|~n",
[I, Pow7, R]),
I1 is I + 2,
(N < I1, !; rootspow7(I1, N)).
main :-
format("isqrt(i) for 0 <= i <= 65:~2n"),
roots(65),
format("~3n"),
format("isqrt(7**i) for 1 <= i <= 73, i odd:~2n"),
format("~t~s~2|~t~s~87|~t~s~131|~n",
["i", "7**i", "isqrt(7**i)"]),
format("-----------------------------------------------------------------------------------------------------------------------------------~n"),
rootspow7(73),
halt.
:- initialization(main).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Instructions for GNU Emacs--
%%% local variables:
%%% mode: prolog
%%% prolog-indent-width: 2
%%% end:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

View file

@ -0,0 +1,14 @@
def isqrt ( x ):
q = 1
while q <= x :
q *= 4
z,r = x,0
while q > 1 :
q /= 4
t,r = z-r-q,r/2
if t >= 0 :
z,r = t,r+q
return r
print ' '.join( '%d'%isqrt( n ) for n in xrange( 66 ))
print '\n'.join( '{0:114,} = isqrt( 7^{1:3} )'.format( isqrt( 7**n ),n ) for n in range( 1,204,2 ))

View file

@ -0,0 +1,39 @@
[ dup size 3 / times
[ char , swap
i 1+ -3 * stuff ]
dup 0 peek char , =
if [ behead drop ] ] is +commas ( $ --> $ )
[ over size -
space swap of
swap join ] is justify ( $ n --> $ )
[ 1
[ 2dup < not while
2 << again ]
0
[ over 1 > while
dip
[ 2 >>
2dup - ]
dup 1 >>
unrot -
dup 0 < iff drop
else
[ 2swap nip
rot over + ]
again ]
nip swap ] is sqrt ( n --> n n )
( sqrt returns the integer square root and remainder )
( i.e. isqrt of 28 is 5 remainder 3 as (5^2)+3 = 28 )
( To make it task compliant change the last line to )
( "nip nip ] is sqrt ( n --> n )" )
66 times [ i^ sqrt drop echo sp ] cr cr
73 times
[ 7 i^ 1+ ** sqrt drop
number$ +commas 41 justify
echo$ cr
2 step ]

View file

@ -0,0 +1,46 @@
/*REXX program computes and displays the Isqrt (integer square root) of some integers.*/
numeric digits 200 /*insure 'nuff decimal digs for results*/
parse arg range power base . /*obtain optional arguments from the CL*/
if range=='' | range=="," then range= 0..65 /*Not specified? Then use the default.*/
if power=='' | power=="," then power= 1..73 /* " " " " " " */
if base =='' | base =="," then base = 7 /* " " " " " " */
parse var range rLO '..' rHI; if rHI=='' then rHI= rLO /*handle a range? */
parse var power pLO '..' pHI; if pHI=='' then pHI= pLO /* " " " */
$=
do j=rLO to rHI while rHI>0 /*compute Isqrt for a range of integers*/
$= $ commas( Isqrt(j) ) /*append the Isqrt to a list for output*/
end /*j*/
$= strip($) /*elide the leading blank in the list. */
say center(' Isqrt for numbers: ' rLO " ──► " rHI' ', length($), "")
say strip($) /*$ has a leading blank for 1st number*/
say
z= base ** pHI /*compute max. exponentiation product.*/
Lp= max(30, length( commas( z) ) ) /*length of " " " */
Lr= max(20, length( commas( Isqrt(z) ) ) ) /* " " " " " Isqrt of above.*/
say 'index' center(base"**index", Lp) center('Isqrt', Lr) /*show a title.*/
say '' copies("", Lp) copies('', Lr) /* " " header*/
do j=pLO to pHI by 2 while pHI>0; x= base ** j
say center(j, 5) right( commas(x), Lp) right( commas( Isqrt(x) ), Lr)
end /*j*/ /* [↑] show a bunch of powers & Isqrt.*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
Isqrt: procedure; parse arg x /*obtain the only passed argument X. */
x= x % 1 /*convert possible real X to an integer*/ /* ◄■■■■■■■ optional. */
q= 1 /*initialize the Q variable to unity.*/
do until q>x /*find a Q that is greater than X. */
q= q * 4 /*multiply Q by four. */
end /*until*/
r= 0 /*R: will be the integer sqrt of X. */
do while q>1 /*keep processing while Q is > than 1*/
q= q % 4 /*divide Q by four (no remainder). */
t= x - r - q /*compute a temporary variable. */
r= r % 2 /*divide R by two (no remainder). */
if t >= 0 then do /*if T is non─negative ... */
x= t /*recompute the value of X */
r= r + q /* " " " " R */
end
end /*while*/
return r /*return the integer square root of X. */

View file

@ -0,0 +1,42 @@
#lang racket
;; Integer Square Root (using Quadratic Residue)
(define (isqrt x)
(define q-init ; power of 4 greater than x
(let loop ([acc 1])
(if (<= acc x) (loop (* acc 4)) acc)))
(define-values (z r q)
(let loop ([z x] [r 0] [q q-init])
(if (<= q 1)
(values z r q)
(let* ([q (/ q 4)]
[t (- z r q)]
[r (/ r 2)])
(if (>= t 0)
(loop t (+ r q) q)
(loop z r q))))))
r)
(define (format-with-commas str #:chunk-size [size 3])
(define len (string-length str))
(define len-mod (modulo len size))
(define chunks
(for/list ([i (in-range len-mod len size)])
(substring str i (+ i size))))
(string-join (if (= len-mod 0)
chunks
(cons (substring str 0 len-mod) chunks))
","))
(displayln "Isqrt of integers (0 -> 65):")
(for ([i 66])
(printf "~a " (isqrt i)))
(displayln "\n\nIsqrt of odd powers of 7 (7 -> 7^73):")
(for/fold ([num 7]) ([i (in-range 1 74 2)])
(printf "Isqrt(7^~a) = ~a\n"
i
(format-with-commas (number->string (isqrt num))))
(* num 49))

View file

@ -0,0 +1,14 @@
use Lingua::EN::Numbers;
sub isqrt ( \x ) { my ( $X, $q, $r, $t ) = x, 1, 0 ;
$q +<= 2 while $q $X ;
while $q > 1 {
$q +>= 2; $t = $X - $r - $q; $r +>= 1;
if $t 0 { $X = $t; $r += $q }
}
$r
}
say (^66)».&{ isqrt $_ }.Str ;
(1, 373)».&{ "7**$_: " ~ comma(isqrt 7**$_) }».say

View file

@ -0,0 +1,25 @@
module Commatize
refine Integer do
def commatize
self.to_s.gsub( /(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/, "\\1,\\2")
end
end
end
using Commatize
def isqrt(x)
q, r = 1, 0
while (q <= x) do q <<= 2 end
while (q > 1) do
q >>= 2; t = x-r-q; r >>= 1
if (t >= 0) then x, r = t, r+q end
end
r
end
puts (0..65).map{|n| isqrt(n) }.join(" ")
1.step(73, 2) do |n|
print "#{n}:\t"
puts isqrt(7**n).commatize
end

View file

@ -0,0 +1,51 @@
use num::BigUint;
use num::CheckedSub;
use num_traits::{One, Zero};
fn isqrt(number: &BigUint) -> BigUint {
let mut q: BigUint = One::one();
while q <= *number {
q <<= &2;
}
let mut z = number.clone();
let mut result: BigUint = Zero::zero();
while q > One::one() {
q >>= &2;
let t = z.checked_sub(&result).and_then(|diff| diff.checked_sub(&q));
result >>= &1;
if let Some(t) = t {
z = t;
result += &q;
}
}
result
}
fn with_thousand_separator(s: &str) -> String {
let digits: Vec<_> = s.chars().rev().collect();
let chunks: Vec<_> = digits
.chunks(3)
.map(|chunk| chunk.iter().collect::<String>())
.collect();
chunks.join(",").chars().rev().collect::<String>()
}
fn main() {
println!("The integer square roots of integers from 0 to 65 are:");
(0_u32..=65).for_each(|n| print!("{} ", isqrt(&n.into())));
println!("\nThe integer square roots of odd powers of 7 from 7^1 up to 7^74 are:");
(1_u32..75).step_by(2).for_each(|exp| {
println!(
"7^{:>2}={:>83} ISQRT: {:>42} ",
exp,
with_thousand_separator(&BigUint::from(7_u8).pow(exp).to_string()),
with_thousand_separator(&isqrt(&BigUint::from(7_u8).pow(exp)).to_string())
)
});
}

View file

@ -0,0 +1,41 @@
comment
return integer square root of n using quadratic
residue algorithm. WARNING: the function will fail
for x > 16,383.
end
function isqrt(x = integer) = integer
var q, r, t = integer
q = 1
while q <= x do
q = q * 4 rem overflow may occur here!
r = 0
while q > 1 do
begin
q = q / 4
t = x - r - q
r = r / 2
if t >= 0 then
begin
x = t
r = r + q
end
end
end = r
rem - Exercise the function
var n, pow7 = integer
print "Integer square root of first 65 numbers"
for n=1 to 65
print using "#####";isqrt(n);
next n
print
print "Integer square root of odd powers of 7"
print " n 7^n isqrt"
print "------------------"
for n=1 to 3 step 2
pow7 = 7^n
print using "### #### ####";n; pow7; isqrt(pow7)
next n
end

View file

@ -0,0 +1,10 @@
function isqrt(x = integer) = integer
var x0, x1 = integer
x1 = x
repeat
begin
x0 = x1
x1 = (x0 + x / x0) / 2
end
until x1 >= x0
end = x0

View file

@ -0,0 +1,40 @@
(import (scheme base))
(import (scheme write))
(import (format)) ;; Common Lisp formatting for CHICKEN Scheme.
(define (find-a-power-of-4-greater-than-x x)
(let loop ((q 1))
(if (< x q)
q
(loop (* 4 q)))))
(define (isqrt+remainder x)
(let loop ((q (find-a-power-of-4-greater-than-x x))
(z x)
(r 0))
(if (= q 1)
(values r z)
(let* ((q (truncate-quotient q 4))
(t (- z r q))
(r (truncate-quotient r 2)))
(if (negative? t)
(loop q z r)
(loop q t (+ r q)))))))
(define (isqrt x)
(let-values (((q r) (isqrt+remainder x)))
q))
(format #t "isqrt(i) for ~D <= i <= ~D:~2%" 0 65)
(do ((i 0 (+ i 1)))
((= i 65))
(format #t "~D " (isqrt i)))
(format #t "~D~3%" (isqrt 65))
(format #t "isqrt(7**i) for ~D <= i <= ~D, i odd:~2%" 1 73)
(format #t "~2@A ~84@A ~43@A~%" "i" "7**i" "sqrt(7**i)")
(format #t "~A~%" (make-string 131 #\-))
(do ((i 1 (+ i 2)))
((= i 75))
(let ((7**i (expt 7 i)))
(format #t "~2D ~84:D ~43:D~%" i 7**i (isqrt 7**i))))

View file

@ -0,0 +1,55 @@
$ include "seed7_05.s7i";
include "bigint.s7i";
const func string: commatize (in bigInteger: bigNum) is func
result
var string: stri is "";
local
var integer: index is 0;
begin
stri := str(bigNum);
for index range length(stri) - 3 downto 1 step 3 do
stri := stri[.. index] & "," & stri[succ(index) ..];
end for;
end func;
const func bigInteger: isqrt (in bigInteger: x) is func
result
var bigInteger: r is 0_;
local
var bigInteger: q is 1_;
var bigInteger: z is 0_;
var bigInteger: t is 0_;
begin
while q <= x do
q *:= 4_;
end while;
z := x;
while q > 1_ do
q := q mdiv 4_;
t := z - r - q;
r := r mdiv 2_;
if t >= 0_ then
z := t;
r +:= q;
end if;
end while;
end func;
const proc: main is func
local
var integer: number is 0;
var bigInteger: pow7 is 7_;
begin
writeln("The integer square roots of integers from 0 to 65 are:");
for number range 0 to 65 do
write(isqrt(bigInteger(number)) <& " ");
end for;
writeln("\n\nThe integer square roots of powers of 7 from 7**1 up to 7**73 are:");
writeln("power 7 ** power integer square root");
writeln("----- --------------------------------------------------------------------------------- -----------------------------------------");
for number range 1 to 73 step 2 do
writeln(number lpad 2 <& commatize(pow7) lpad 85 <& commatize(isqrt(pow7)) lpad 42);
pow7 *:= 49_;
end for;
end func;

View file

@ -0,0 +1,3 @@
var n = 1234
say n.isqrt
say n.iroot(2)

View file

@ -0,0 +1,10 @@
func rootint(n, k=2) {
return 0 if (n == 0)
var (s, v) = (n, k - 1)
loop {
var u = ((v*s + (n // s**v)) // k)
break if (u >= s)
s = u
}
s
}

View file

@ -0,0 +1,8 @@
func isqrt(x) { var (q, r) = (1, 0); while (q <= x) { q <<= 2 }
while (q > 1) { q >>= 2; var t = x-r+q; r >>= 1
if (t >= 0) { (x, r) = (t, r+q) } } r }
say isqrt.map(0..65).join(' '); printf("\n")
for n in (1..73 `by` 2) {
printf("isqrt(7^%-2d): %42s\n", n, isqrt(7**n).commify) }

View file

@ -0,0 +1,124 @@
(*
The Rosetta Code integer square root task, in Standard ML.
Compile with, for example:
mlton isqrt.sml
*)
val zero = IntInf.fromInt (0)
val one = IntInf.fromInt (1)
val seven = IntInf.fromInt (7)
val word1 = Word.fromInt (1)
val word2 = Word.fromInt (2)
fun
find_a_power_of_4_greater_than_x (x) =
let
fun
loop (q) =
if x < q then
q
else
loop (IntInf.<< (q, word2))
in
loop (one)
end;
fun
isqrt (x) =
let
fun
loop (q, z, r) =
if q = one then
r
else
let
val q = IntInf.~>> (q, word2)
val t = z - r - q
val r = IntInf.~>> (r, word1)
in
if t < zero then
loop (q, z, r)
else
loop (q, t, r + q)
end
in
loop (find_a_power_of_4_greater_than_x (x), x, zero)
end;
fun
insert_separators (s, sep) =
(* Insert separator characters (such as #",", #".", #" ") in a numeral
that is already in string form. *)
let
fun
loop (revchars, i, newchars) =
case (revchars, i) of
([], _) => newchars
| (revchars, 3) => loop (revchars, 0, sep :: newchars)
| (c :: tail, i) => loop (tail, i + 1, c :: newchars)
in
implode (loop (rev (explode s), 0, []))
end;
fun
commas (s) =
(* Insert commas in a numeral that is already in string form. *)
insert_separators (s, #",");
val pad_with_spaces = StringCvt.padLeft #" "
fun
main () =
let
val i = ref 0
in
print ("isqrt(i) for 0 <= i <= 65:\n\n");
i := 0;
while !i < 65 do (
print (IntInf.toString (isqrt (IntInf.fromInt (!i))));
print (" ");
i := !i + 1
);
print (IntInf.toString (isqrt (IntInf.fromInt (65))));
print ("\n\n\n");
print ("isqrt(7**i) for 1 <= i <= 73, i odd:\n\n");
print (pad_with_spaces 2 "i");
print (pad_with_spaces 85 "7**i");
print (pad_with_spaces 44 "sqrt(7**i)");
print ("\n");
i := 1;
while !i <= 131 do (
print ("-");
i := !i + 1
);
print ("\n");
i := 1;
while !i <= 73 do (
let
val pow7 = IntInf.pow (seven, !i)
val root = isqrt (pow7)
in
print (pad_with_spaces 2 (Int.toString (!i)));
print (pad_with_spaces 85 (commas (IntInf.toString pow7)));
print (pad_with_spaces 44 (commas (IntInf.toString root)));
print ("\n");
i := !i + 2
end
)
end;
main ();
(* local variables: *)
(* mode: sml *)
(* sml-indent-level: 2 *)
(* sml-indent-args: 2 *)
(* end: *)

View file

@ -0,0 +1,60 @@
import BigInt
func integerSquareRoot<T: BinaryInteger>(_ num: T) -> T {
var x: T = num
var q: T = 1
while q <= x {
q <<= 2
}
var r: T = 0
while q > 1 {
q >>= 2
let t: T = x - r - q
r >>= 1
if t >= 0 {
x = t
r += q
}
}
return r
}
func pad(string: String, width: Int) -> String {
if string.count >= width {
return string
}
return String(repeating: " ", count: width - string.count) + string
}
func commatize<T: BinaryInteger>(_ num: T) -> String {
let string = String(num)
var result = String()
result.reserveCapacity(4 * string.count / 3)
var i = 0
for ch in string {
if i > 0 && i % 3 == string.count % 3 {
result += ","
}
result.append(ch)
i += 1
}
return result
}
print("Integer square root for numbers 0 to 65:")
for n in 0...65 {
print(integerSquareRoot(n), terminator: " ")
}
let powerWidth = 83
let isqrtWidth = 42
print("\n\nInteger square roots of odd powers of 7 from 1 to 73:")
print(" n |\(pad(string: "7 ^ n", width: powerWidth)) |\(pad(string: "isqrt(7 ^ n)", width: isqrtWidth))")
print(String(repeating: "-", count: powerWidth + isqrtWidth + 6))
var p: BigInt = 7
for n in stride(from: 1, through: 73, by: 2) {
let power = pad(string: commatize(p), width: powerWidth)
let isqrt = pad(string: commatize(integerSquareRoot(p)), width: isqrtWidth)
print("\(pad(string: String(n), width: 2)) |\(power) |\(isqrt)")
p *= 49
}

View file

@ -0,0 +1,28 @@
10 LET X = 0
20 GOSUB 100
30 PRINT R
40 LET X = X + 1
50 IF X < 66 THEN GOTO 20
70 PRINT "---"
71 LET X = 7
72 GOSUB 100
73 PRINT R
77 LET X = 343
78 GOSUB 100
79 PRINT R
90 END
100 REM integer square root function
110 LET Q = 1
120 IF Q > X THEN GOTO 150
130 LET Q = Q * 4
140 GOTO 120
150 LET Z = X
160 LET R = 0
170 IF Q <= 1 THEN RETURN
180 LET Q = Q / 4
190 LET T = Z - R - Q
200 LET R = R / 2
210 IF T < 0 THEN GOTO 170
220 LET Z = T
230 LET R = R + Q
240 GOTO 170

View file

@ -0,0 +1,58 @@
function isqrt {
typeset -i x
for x; do
typeset -i q=1
while (( q <= x )); do
(( q <<= 2 ))
if (( q <= 0 )); then
return 1
fi
done
typeset -i z=x
typeset -i r=0
typeset -i t
while (( q > 1 )); do
(( q >>= 2 ))
(( t = z - r - q ))
(( r >>= 1 ))
if (( t >= 0 )); then
(( z = t ))
(( r = r + q ))
fi
done
printf '%d\n' "$r"
done
}
# demo
printf 'isqrt(n) for n from 0 to 65:\n'
for i in {1..4}; do
for n in {0..65}; do
case $i in
1)
(( tens=n/10 ))
if (( tens )); then
printf '%2d' "$tens"
else
printf ' '
fi
;;
2) printf '%2d' $(( n%10 ));;
3) printf -- '--';;
4) printf '%2d' "$(isqrt "$n")";;
esac
done
printf '\n'
done
printf '\n'
printf 'isqrt(7ⁿ) for odd n up to the limit of integer precision:\n'
printf '%2s|%27sⁿ|%14sⁿ)\n' "n" "7" "isqrt(7"
for (( i=0;i<48; ++i )); do printf '-'; done; printf '\n'
for (( p=1; p<=73 && (n=7**p) > 0; p+=2)); do
if r=$(isqrt $n); then
printf "%2d|%'28d|%'16d\n" "$p" "$n" "$r"
else
break
fi
done

View file

@ -0,0 +1,38 @@
1000 X=0
1010 #=2000
1020 $=32
1030 ?=R
1040 X=X+1
1050 #=X=33=0*1070
1060 ?=""
1070 #=X<66*1010
1080 P=1
1090 X=7
1100 #=2000
1110 ?=""
1120 ?="Root 7^";
1130 ?=P
1140 ?="(";
1150 ?=X
1160 ?=") = ";
1170 ?=R
1180 X=X*49
1190 P=P+2
1200 #=P<6*1100
1210 #=9999
2000 A=!
2010 Q=1
2020 #=X>Q=0*2050
2030 Q=Q*4
2040 #=2020
2050 Z=X
2060 R=0
2070 #=Q<2*A
2080 Q=Q/4
2090 T=Z-R-Q
2100 I=Z<(R+Q)
2110 R=R/2
2120 #=I*2070
2130 Z=T
2140 R=R+Q
2150 #=2070

View file

@ -0,0 +1,34 @@
Imports System
Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Function isqrt(ByVal x As BI) As BI
Dim t As BI, q As BI = 1, r As BI = 0
While q <= x : q <<= 2 : End While
While q > 1 : q >>= 2 : t = x - r - q : r >>= 1
If t >= 0 Then x = t : r += q
End While : Return r
End Function
Sub Main()
Const max As Integer = 73, smax As Integer = 65
Dim power_width As Integer = ((BI.Pow(7, max).ToString().Length \ 3) << 2) + 3,
isqrt_width As Integer = (power_width + 1) >> 1,
n as Integer
WriteLine("Integer square root for numbers 0 to {0}:", smax)
For n = 0 To smax : Write("{0} ", (n \ 10).ToString().Replace("0", " "))
Next : WriteLine()
For n = 0 To smax : Write("{0} ", n Mod 10) : Next : WriteLine()
WriteLine(New String("-"c, (smax << 1) + 1))
For n = 0 To smax : Write("{0} ", isqrt(n)) : Next
WriteLine(vbLf & vbLf & "Integer square roots of odd powers of 7 from 1 to {0}:", max)
Dim s As String = String.Format("[0,2] |[1,{0}:n0] |[2,{1}:n0]",
power_width, isqrt_width).Replace("[", "{").Replace("]", "}")
WriteLine(s, "n", "7 ^ n", "isqrt(7 ^ n)")
WriteLine(New String("-"c, power_width + isqrt_width + 6))
Dim p As BI = 7 : n = 1 : While n <= max
WriteLine(s, n, p, isqrt(p)) : n += 2 : p = p * 49
End While
End Sub
End Module

View file

@ -0,0 +1,38 @@
import "/big" for BigInt
import "/fmt" for Fmt
var isqrt = Fn.new { |x|
if (!(x is BigInt && x >= BigInt.zero)) {
Fiber.abort("Argument must be a non-negative big integer.")
}
var q = BigInt.one
while (q <= x) q = q * 4
var z = x
var r = BigInt.zero
while (q > BigInt.one) {
q = q >> 2
var t = z - r - q
r = r >> 1
if (t >= 0) {
z = t
r = r + q
}
}
return r
}
System.print("The integer square roots of integers from 0 to 65 are:")
for (i in 0..65) System.write("%(isqrt.call(BigInt.new(i))) ")
System.print()
System.print("\nThe integer square roots of powers of 7 from 7^1 up to 7^73 are:\n")
System.print("power 7 ^ power integer square root")
System.print("----- --------------------------------------------------------------------------------- -----------------------------------------")
var pow7 = BigInt.new(7)
var bi49 = BigInt.new(49)
var i = 1
while (i <= 73) {
Fmt.print("$2d $,84s $,41s", i, pow7, isqrt.call(pow7))
pow7 = pow7 * bi49
i = i + 2
}

View file

@ -0,0 +1,35 @@
// Rosetta Code problem: https://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
// by Jjuanhdez, 06/2022
print "Integer square root of first 65 numbers:"
for n = 1 to 65
print isqrt(n) using("##");
next n
print : print
print "Integer square root of odd powers of 7"
print " n | 7^n | isqrt "
print "----|--------------------|-----------"
for n = 1 to 21 step 2
pow7 = 7 ^ n
print n using("###"), " | ", left$(str$(pow7,"%20.1f"),18), " | ", left$(str$(isqrt(pow7),"%11.1f"),9)
next n
end
sub isqrt(x)
q = 1
while q <= x
q = q * 4
wend
r = 0
while q > 1
q = q / 4
t = x - r - q
r = r / 2
if t >= 0 then
x = t
r = r + q
end if
wend
return int(r)
end sub