Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect algorithm in the prime numbers calculation benchmarks #118

Closed
t-w opened this issue Aug 2, 2023 · 2 comments
Closed

Incorrect algorithm in the prime numbers calculation benchmarks #118

t-w opened this issue Aug 2, 2023 · 2 comments

Comments

@t-w
Copy link
Collaborator

t-w commented Aug 2, 2023

If I understand correctly what the sieve.pas benchmarks tests are supposed to do (count primes up to a certain number, 8192 in the tests) - the algorithm used to calculate primes:

    fillchar(flags, sizeof(flags), true);
    count := 0;
    for i:=0 to size do
         if flags[i] then begin
             prime := i*2 + 3;
             k := prime + i;
             while (k <= size) do begin
                 flags[k] := false;
                 inc(k, prime);
             end;
             inc(count);
         end;

is not correct - it counts 1899 primes while up to 8192 (what is calculated), there are only 1028.

The corrected algorithm would be:

    fillchar(flags, sizeof(flags), true);
    flags[0] := false;
    flags[1] := false;
    count := 0;
    for i:=2 to size do
	if flags[i] then 
        { mark all multiplications of i as non-primes }
        begin
	    k := i + i;
	    while (k <= size) do
	    begin
		flags[k] := false;
		inc(k,i);
	    end;
	    inc(count);
	end;

as the inner part has to mark all multiplications of the current prime.
The other algorithm just does not mark many non-primes (it seems like an optimization to faster find the next prime - but it does not seem to be used correctly here...).

Also, in consequence, this cheats a bit on the result of the benchmark (by more than a 100 'ticks')...

@t-w
Copy link
Collaborator Author

t-w commented Aug 3, 2023

OK. I see. That algorithm does indeed something a bit different than it seemed at first glance - it does not store information about primes it finds (what could be easily added, eg in a second array), it just counts them, using the array in a more packed way.

Interesting, thanks for checking.

@t-w t-w closed this as completed Aug 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants