Reputation: 9
I'm trying to do it as fast as it is possible. What I can not figure out is how to put all the divisors into the array, and sort that array after that.
I've optimized the for loop - it ends with sqrt(n).
I've also refactored my code, but it still doesn't pass all the tests
type output = array of longint;
var
grater,lower: output;
n,i,v,counter:longint;
begin
read(n);
setLength(grater, round(Sqrt(n)));
setLength(lower, round(Sqrt(n)));
counter:= 0;
for i:=1 to round(Sqrt(n)) do
begin
if (n mod i = 0) then
begin
if i>round(Sqrt(n)) then
grater[counter]:= i
else
lower[counter]:=i;
if n div i>round(Sqrt(n)) then
grater[counter]:= n div i
else
lower[counter]:=n div i;
counter:= counter +1;
end;
end;
for v:=0 to Length(lower) do
begin
if (lower[v] <> 0) then writeln(lower[v]);
end;
for v:=Length(grater)-1 downto 0 do
begin
if grater[v] <> 0 then writeln(grater[v]);
end;
end.
Upvotes: 0
Views: 420
Reputation: 28312
It looks like what you're doing is this:
So for input 12, your output might look like:
2
6
3
4
An easy way to adjust what you have is to use two lists for your answers: the first list will record factors less than sqrt(input) in ascending order, and the second will record factors greater than sqrt(input) in descending order. Then, to print them out in order, simply print the contents of the first list in order, and follow up with the contents of the second list in reverse order.
Upvotes: 2