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="
program LowSquareStartN;
uses
sysutils;
function LowSquareStartN(N: Uint32):
dez = 10.0;▼
{Find lowest square that matches N}
var
sqrtN,sqrtN_10,dez : double;
mySqr : Uint64;
Pow10 : int64;
begin
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;
if mySqr = n then EXIT;
//test only next number
inc(result);
mySqr := (result*result);
if mySqr = n then EXIT;
pow10 *= 10;
result := Trunc(sqrtN_10);
mySqr := result*result;
if mySqr = n then EXIT;
inc(result);
mySqr := result*result;
if mySqr = n then EXIT;
pow10 *= 10;
sqrtN *= dez;
sqrtN_10 *=dez;
until sqrtN >
exit(0);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
begin
T:=LowSquareStartN(I);
Line 2,088 ⟶ 2,091:
end;
writeln;
writeln;
writeln('Test 999,991 .. 1,000,000');
for I:=
begin
T:= LowSquareStartN(I);
writeln(i:10,':',T:
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>▼
▲</syntaxhighlight>
{{out|@home}}
<pre>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
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;
|