Pascal: Prime Factors

program ex29;

var   a, i, replica, limit : integer;
        prime: Boolean;

begin
  writeln ('Prime Factors');
  writeln ('Enter the number whose prime factors you want to find');
  readln (a);
  replica := a;
  limit := a div 2;
  prime := true;
  i := 2;
  repeat
    while (replica  mod i = 0) do
      begin
        writeln (i, ' is a prime factor of ', a);
        replica := replica div i;
      end;
    inc (i);
  until (replica = 1) or (i > limit);
  if replica < a then prime := false;
  if prime then writeln (a, ' is prime;');
  readln;
end.

This problem is solved by a loop within a loop. A divisor is a factor if number mod divisor = 0; Work from examples, eg 24:

24 mod 2 = 0, output 2, do replica = 24/2=12
12 mod 2 = 0, output 2, do replica = 12/2=6
 6  mod 2 = 0, output 2, do replica = 6/2=3
 3  mod 2 = 1, no output, inc 2 to 3
 6  mod 3 = 0, output 3, do replica = 3/3=1
 replica = 1 so finish

eg 26:

26 mod 2 = 0, output 2, do replica = 26/2=13
13 mod 2 = 1, no output , inc 2 to 3
13 mod 3 = 1, no output, inc 3 to 4
13 mod 4 = 1, no output, inc 4 to 5
13 mod 5 = 3, no output, inc 5 to 6
13 mod 6 = 1, no output, inc 6 to 7
13 mod 7 = 6, no output, inc 7 to 8
13 mod 8 = 3, no output, inc 8 to 9
13 mod 9 = 4, no output, inc 9 to 10
13 mod 10 = 3, no output, inc 9 to 11
13 mod 11 = 2, no output, inc 10 to 12
13 mod 12 = 1, no output, inc 11 to 13
13 mod 13 = 0, output 13, do 13/13=1
replica is now 1 so loop stops 

We divide the number by the loop counter until the remainder is non-zero. Where the remainder is non-zero we increment the loop counter. As the number comes down in size the loop counter goes up, which gives us our finishing condition, number < counter.

Now try 2, 3, 4, 5, 29, etc. until you are satisfied that the algorithm works. Then try coding it.

Back to questions