I have a function FIsPrime
which takes a int64
and returns a boolean True or False depending on whether the given int64
is prime or not.
function FIsPrime(P:int64):boolean;
var
I:int64;
RSqrtP:Extended;
begin
I:= 3;
RSqrtP := sqrt(P) + 1;
while ((P mod I) <> 0) AND (I <= RSqrtP) AND ((P mod 2) <> 0) do
I := I + 2;
if I < RSqrtP then
FIsPrime := False
else
FIsPrime := True;
end;
However, while this works, it's quite slow. To check the numbers from 106 to 5×106 takes 4 seconds.
I'm testing numbers on the order of 1012 and 1015 - the whole code picks a random number and × it by 1012 to get a large random number.
This random number is run through the FIsPrime
function and incremented by 1 untill it is prime:
function FFirstPrimeAbove(P:int64):int64;
var
BIsPrime: boolean;
begin
if P mod 2 = 0 then
inc(P);
repeat
BIsPrime := FIsPrime(P);
P := P + 2;
until (BIsPrime);
FFirstPrimeAbove := P;
end;
This can take a while - around 6 seconds for 1012 and 7 for 1015.
While 14 seconds isn't much, it is annoying. Is there a way to reduce this time with a more efficient algorithm?
I'm fairly new to Pascal, but have been programming for years - so any more efficient algorithm would be useful.
I looked at the AKS Test but there is a lot of jargon to overcome - "polynomial congruence relation", "generalization to polynomials" and "binomial coefficient" to pick a few.
Any basic hints as to how I could implement something in Delphi would be appreciated.
FIsPrime
? What is the F for? Assign the bool like this:somebool := somecondition
. – David Heffernan