How to calculate all the less than 500 additive prime numbers in Pascal

1 Answer

0 votes
// Additive primes: primes whose sum of digits is also prime

program AdditivePrimes;

{$mode objfpc}{$H+}

uses
  SysUtils;

// Check if a number is prime
function IsPrime(n: LongWord): Boolean;
var
  i: LongWord;
begin
  if n < 2 then
    Exit(False);
  if (n mod 2 = 0) then
    Exit(n = 2);
  if (n mod 3 = 0) then
    Exit(n = 3);

  i := 5;
  while i * i <= n do
  begin
    if (n mod i = 0) then
      Exit(False);
    Inc(i, 2);
    if (n mod i = 0) then
      Exit(False);
    Inc(i, 4);
  end;

  Result := True;
end;

// Compute the sum of digits of a number
function SumDigits(n: LongWord): LongWord;
var
  sum: LongWord;
begin
  sum := 0;
  while n > 0 do
  begin
    sum := sum + (n mod 10);
    n := n div 10;
  end;
  Result := sum;
end;

// Check if a number is an additive prime
function IsAdditivePrime(n: LongWord): Boolean;
begin
  Result := IsPrime(n) and IsPrime(SumDigits(n));
end;

var
  n: LongWord;
  count: Integer;

begin
  count := 0;

  for n := 1 to 499 do
  begin
    if IsAdditivePrime(n) then
    begin
      Write(n:3);
      Inc(count);
      if (count mod 10 = 0) then
        WriteLn
      else
        Write(' ');
    end;
  end;

  WriteLn;
  WriteLn;
  WriteLn('Total additive primes = ', count);
end.



(*
run:

 61  67  83  89 101 113 131 137 139 151
157 173 179 191 193 197 199 223 227 229
241 263 269 281 283 311 313 317 331 337
353 359 373 379 397 401 409 421 443 449
461 463 467 487 

Total additive primes = 54

*)

 



answered May 4 by avibootz
...