How to find all divisors of a number in Pascal

1 Answer

0 votes
program EfficientDivisors;

{$mode objfpc}

uses Math;

type
  TIntArray = array of Integer;

{
  Function: FindDivisors
  Purpose: Efficiently find all divisors of a number using sqrt(n).

  Explanation:
    - We loop only up to Sqrt(n), which reduces the number of iterations.
    - If i divides n, then both i and n div i are divisors.
    - If i = n div i (perfect square), we add it only once.
    - We store divisors in a dynamic array and sort them manually.
}
function FindDivisors(n: Integer): TIntArray;
var
  divisors: TIntArray;
  i, limit, pair, count, j, temp: Integer;
begin
  count := 0;
  limit := Trunc(Sqrt(n));

  for i := 1 to limit do
  begin
    if (n mod i = 0) then
    begin
      // Add i
      SetLength(divisors, count + 1);
      divisors[count] := i;
      Inc(count);

      // Add n div i if different
      pair := n div i;
      if (i <> pair) then
      begin
        SetLength(divisors, count + 1);
        divisors[count] := pair;
        Inc(count);
      end;
    end;
  end;

  // Sort the array (simple bubble sort)
  for i := 0 to count - 2 do
    for j := i + 1 to count - 1 do
      if divisors[i] > divisors[j] then
      begin
        temp := divisors[i];
        divisors[i] := divisors[j];
        divisors[j] := temp;
      end;

  Result := divisors;
end;

var
  num: Integer;
  result: TIntArray;
  i: Integer;
begin
  num := 24;

  result := FindDivisors(num);

  Write('Divisors of ', num, ': [');
  for i := 0 to High(result) do
  begin
    Write(result[i]);
    if i < High(result) then
      Write(', ');
  end;
  WriteLn(']');
end.


(*
run:

Divisors of 24: [1, 2, 3, 4, 6, 8, 12, 24]

*)




answered 4 days ago by avibootz
...