Carian12
Carian12

Reputation: 9

How to find the divisors of a number and print them out in ascending order?

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

Answers (1)

Patrick87
Patrick87

Reputation: 28312

It looks like what you're doing is this:

  1. check all integers from 2 up to sqrt(n)
  2. if the input is divisible by the integer, record the integer and (input/integer)

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

Related Questions