Smallest square that begins with n: Difference between revisions

m
→‎{{header|Free Pascal}}: already know the power of 10 to divide with.
m (→‎{{header|Phix}}: use pygments, added trans Pascal (neat answer, btw))
m (→‎{{header|Free Pascal}}: already know the power of 10 to divide with.)
Line 2,032:
</pre>
 
<syntaxhighlight lang="perlpascal">
program LowSquareStartN;
uses
sysutils;
 
function LowSquareStartN(N: Uint32): Uint32;
const
dez = 10.0;
{Find lowest square that matches N}
var
sqrtN,sqrtN_10,dez : double;
mySqr : Uint64;
Pow10 : int64;
begin
dez := 10.0;
Pow10:= 1;
sqrtN := sqrt(n);
//to stay more accurate, instead *sqrt(10);
sqrtN_10 := sqrt(n*dez);// one more decimal digit
mySqr := n;
repeat
result := Trunc(sqrtN);
mySqr := result*result;
while mySqr > n do mySqr := mySqr DIV 10Pow10;
if mySqr = n then EXIT;
//test only next number
inc(result);
mySqr := (result*result);
while mySqr > n do mySqr := mySqr DIV 10pow10;
if mySqr = n then EXIT;
 
pow10 *= 10;
result := Trunc(sqrtN_10);
mySqr := result*result;
while mySqr > n do mySqr := mySqr DIV 10pow10;
if mySqr = n then EXIT;
inc(result);
mySqr := result*result;
while mySqr > n do mySqr := mySqr DIV 10pow10;
if mySqr = n then EXIT;
 
pow10 *= 10;
sqrtN *= dez;
sqrtN_10 *=dez;
until sqrtN > dez*nUint32(-1);
exit(0);readln;
readln;
end;
 
procedure SquareStartsN();
{Find smallest square that begins with N}
var
T : Uint64;
i : Uint32;
begin
writeln('Test 1 .. 49');
for I:=1 to 49 do //1*1000*1000 do
begin
T:=LowSquareStartN(I);
Line 2,088 ⟶ 2,091:
end;
writeln;
writeln;
writeln('Test 999,991 .. 1,000,000');
for I:= 999991 to 1000*1000-9 doto //1000*1000 do
begin
T:= LowSquareStartN(I);
writeln(i:10,':',T:1011,'->',t*t:1420);
end;
writeln;
T := GetTickCount64;
for I:= 1 to 10*1000*1000-10 do
LowSquareStartN(I);
T := GetTickCount64-T;
writeln('check 1..1E7 in ', T,' ms');
end;
 
BEGIN
SquareStartsN();
END.</syntaxhighlight>
END.
 
</syntaxhighlight>
{{out|@home}}
<pre>Test 1 .. 49
Test 1 .. 49
1 25 36 4 529 64 729 81 9 100
1156 121 1369 144 1521 16 1764 1849 196 2025
Line 2,112 ⟶ 2,119:
 
Test 999,991 .. 1,000,000
999991: 3162264-> 9999913605696
999992: 999996-> 999992000016
999993: 3162267-> 9999932579289
999994: 999997-> 999994000009
999995: 316227-> 99999515529
999996: 999998-> 999996000004
999997: 3162273-> 9999970526529
999998: 999999-> 999998000001
999999: 3162277-> 9999995824729
1000000: 1000-> 1000000
 
check 1..1E7 in 328 ms
real 0m0,001s
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>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
132

edits