Smallest square that begins with n: Difference between revisions

→‎{{header|Free Pascal}}: Julia version is neglectable slower, but uses a lot of memory and only useful for continious regions of numbers to test.
(→‎{{header|Free Pascal}}: Julia version is neglectable slower, but uses a lot of memory and only useful for continious regions of numbers to test.)
Line 2,130:
check 1..1E7 in 328 ms
TIO.RUN-> check 1..1E7 in 2540 ms ( old compiler version 3.0.4/3.2.3 and 2.3 vs 4.4 Ghz )
</pre>
===={{trans|Julia}}====
Storing only the root ( n_running ) of the square so Uint32 suffices for the result.
// 355ms -> 335 ms
<syntaxhighlight lang="pascal">program smsq;
{$IFDEF FPC}{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$ENDIF}
uses
sysutils;
type
tRes = array of Uint32;
 
function smsq(n:Uint32):tRes;
var
k : Uint64;
n_running,found : Uint32;
 
begin
setlength(result,n+1);
fillchar(result[0],length(result)*Sizeof(result[0]),#0);
found := 0;
n_running := 1;
while found < n do
begin
k := sqr(n_running);
while k > 0 do
begin
if (k <= n) AND (result[k] = 0) then
Begin
result[k] := n_running;
found += 1;
end;
k := k div 10;
end;
inc(n_running);
end
end;
 
var
t0 : Int64;
n,i : Uint32;
results : tRes;
BEGIN
n := 49;
results := smsq(n);
For i := 1 to n do
begin
write(sqr(results[i]):6);
if i mod 10 = 0 then
Writeln;
end;
writeln;
n := 10*1000*1000;
// speed up cpu
smsq(n);
t0 := GetTickCount64;
smsq(n);
t0 := GetTickCount64-t0;
writeln('check 1..',n,' in ', T0,' ms');
END.
</syntaxhighlight>
{{out|@home}}
<pre>
1 25 36 4 529 64 729 81 9 100
1156 121 1369 144 1521 16 1764 1849 196 2025
2116 225 2304 2401 25 2601 2704 289 2916 3025
3136 324 3364 3481 35344 36 3721 3844 3969 400
41209 4225 4356 441 45369 4624 4761 484 49
check 1..10000000 in 335 ms
</pre>
 
132

edits