Overview

Factorization

Simple algorithm to find the prime factors of a given integer.

Source Code

// Simple algorithm to find the prime factors of a given integer.
function Factorize(n : Integer) : String;
begin
   if n <= 1 then Exit(IntToStr(n));
   var k := 2;
   var first := True;
   while n >= k do begin
      while (n mod k) = 0 do begin
         if not first then Result += ' * ';
         Result += IntToStr(k);
         n := n div k;
         first := False;
      end;
      Inc(k);
   end;
end;
for var i := 2 to 10 do PrintLn(IntToStr(i) + ' = ' + Factorize(i));

Result

2 = 2
3 = 3
4 = 2 * 2
5 = 5
6 = 2 * 3
7 = 7
8 = 2 * 2 * 2
9 = 3 * 3
10 = 2 * 5
On this page