Hello everyone,
I'm new here - just joined.
I'm strugling with a bit of code. Im trying to check if a number is a prime number, but my program produces weird results.
Herse the code:
{ Vefies if a value is prime. }
function TMactacHash.IsPrime(value: integer): boolean;
var
i, overValue: integer;
flag: boolean;
begin
flag := true;
for i := 1 to value do
begin
overValue := value mod i;
if overValue = 0 then
flag := false;
WriteLn(IntToStr(value) + ' mod ' + IntToStr(i) + ' = ' + IntToStr(overValue));
readln;
end;
Result := flag;
end;
{ Generates the prime number. }
function TMactacHash.GeneratePrime(primeCounter: integer; _set: PrimeSets): integer;
var
primeNumber: integer;
flag: boolean;
begin
primeNumber := primeCounter;
flag := false;
while not flag do
begin
if _set = SET1 then
Inc(primeNumber)
else if _set = SET2 then
Inc(primeNumber, 2)
else if _set = SET3 then
Inc(primeNumber, 3)
else if _set = SET4 then
Inc(primeNumber, 4)
else if _set = SET5 then
Inc(primeNumber, 5)
else if _set = SET6 then
Inc(primeNumber, 6)
else if _set = SET7 then
Inc(primeNumber, 7)
else if _set = SET8 then
Inc(primeNumber, 8 + 8);
if IsPrime(primeNumber) then
flag := true;
end;
Result := primeNumber;
end;
{ Populates the prime sets with prime numbers. }
procedure TMactacHash.PopulatePrimeSets();
var
i, primeNumber: integer;
begin
primeNumber := 2;
for i := 0 to MAX_TIMES do
begin
primeNumber := GeneratePrime(primeNumber, SET1);
primeSet1[i] := primeNumber;
end;
end;
And here is my output:
3 mod 1 = 0
3 mod 2 = 1
3 mod 3 = 0
4 mod 1 = 0
4 mod 2 = 0
4 mod 3 = 1
4 mod 4 = 0
...
As you can see it mods 3 and 4 over and over. Why does it do this and how can I fix it. Is there maybe a more efficient way of checking if numbers are prime or not?
Thanks in advance.