How to find A and B where A and B are prime numbers and A * B = 12349 in Pascal

1 Answer

0 votes
program FindABProgram;

{$mode objfpc}

uses
  Math;

// Function to check if a number is prime
function isPrime(n: Integer): Boolean;
var
  limit, i: Integer;
begin
  if n <= 1 then Exit(False);
  if n <= 3 then Exit(True);
  if (n mod 2 = 0) or (n mod 3 = 0) then Exit(False);

  limit := Trunc(Sqrt(n));
  i := 5;
  while i <= limit do
  begin
    if (n mod i = 0) or (n mod (i + 2) = 0) then
      Exit(False);
    Inc(i, 6);
  end;

  Result := True;
end;

// Function to find the two prime factors A and B
procedure findAB(N: Integer; var A, B: Integer);
var
  limit, i, j: Integer;
begin
  limit := Trunc(Sqrt(N));  

  for i := 2 to limit do
  begin
    if (N mod i = 0) then
    begin
      j := N div i;
      if isPrime(i) and isPrime(j) then
      begin
        A := i;
        B := j;
        Exit;
      end;
    end;
  end;

  A := -1;
  B := -1; // No prime factors found
end;

var
  N, A, B: Integer;

begin
  N := 12349;

  findAB(N, A, B);

  if A <> -1 then
    WriteLn('A = ', A, ', B = ', B)
  else
    WriteLn('Not found.');
end.



(*
run:

A = 53, B = 233

*)

 



answered Jun 5 by avibootz
edited Jun 5 by avibootz

Related questions

...