Testing primality with Free Pascal
I refined my Free Pascal program to accept 64-bit unsigned integers, which allows up to 19 decimal digits. However, testing with Big Primes, it is only usable up to 15 decimal digits on my Raspberry Pi 4. Any bigger primes take forever to test, in human perspective. The problem seems to be in how primes are generated in the primality test. The prime number generator uses a simple algorithm of odd numbers greater than one, and less than the square root of of the number of which its primality is tested. For small numbers it’s fine, but for larger numbers testing with odd numbers instead of actual prime numbers is a bit of waste of precious CPU time.
Still, being able to test primality with a relatively simple algorithm is rather awesome as a first attempt.
The slow-down in the algorithm is not caused by testing primality, but by the inefficiency of generating prime numbers. So I need a faster algorithm to do just that. I’ve looked around, but it requires me to learn new concepts in mathematics. I could do that, or, come back to it later when I’m more versed in writing in Pascal, or even stop here, since I don’t really have any incentives to create a full-blown efficient prime number generator, in other words, reinvent the wheel.
program isPrime3;
uses crt;
const
zero : qword = 0;
one : qword = 1;
two : qword = 2;
three : qword = 3;
var
num : qword;
again : char;
function isprime(num : qword) : boolean;
var
iscomposite : boolean;
test : qword;
begin
if num = one then
isprime := false
else
if (num = two) or (num = three) then
isprime := true
else
if (num mod two) = zero then
isprime := false
else begin
iscomposite := false;
test := three;
while (test * test) <= num do begin
if (num mod test) = zero then
iscomposite := true;
test := test + two;
end;
isprime := not iscomposite;
end;
end;
begin
again := 'Y';
while (again ='y') or (again = 'Y') or (again = chr(13)) do begin
num := zero;
while num < one do begin
write('Give a whole positive number: ');
readln(num);
end;
if isprime(num) then
writeln(num, ' is prime')
else
writeln(num, ' is not prime');
write('again? [Y/n] ');
again := readkey;
writeln(again);
end;
end.
P.S. I fixed a bug that caused a press on the Enter key to exit the program, instead of continuing it as I meant it to do. Checking additionally for the Enter key chr(13)
was easy enough. There are still bugs, though, but it’s usable enough for now, as throw-away code, not meant for application in a realworld app.
P.P.S.S. You can test this code on TutorialsPoint, which has a Pascal IDE, you could type the source code in, or copy and paste it from this article.