Skip to content

Builtin prime table up to 20 bits; ulong_extras cleanup#2548

Merged
fredrik-johansson merged 3 commits intoflintlib:mainfrom
fredrik-johansson:isprime3
Jan 12, 2026
Merged

Builtin prime table up to 20 bits; ulong_extras cleanup#2548
fredrik-johansson merged 3 commits intoflintlib:mainfrom
fredrik-johansson:isprime3

Conversation

@fredrik-johansson
Copy link
Copy Markdown
Collaborator

The static bit table of odd primes up to 2^15 is complemented with a static bit table mod 30 up to 2^20 (costing 35 KB), making n_is_prime nearly instantaneous up to 20 bits. We also search these tables directly in n_nextprime, significantly speeding up generating primes up to one million.

Timings for n_is_prime, average for 10^5 random inputs of the given bit size:

bits     old       new     speedup
 1   | 5.66e-09  2.49e-09   2.273x
 2   | 1.02e-08  2.50e-09   4.080x
 3   | 1.06e-08  2.49e-09   4.257x
 4   | 1.13e-08  2.50e-09   4.520x
 5   | 1.29e-08  2.50e-09   5.160x
 6   | 1.49e-08  2.51e-09   5.936x
 7   | 1.61e-08  2.49e-09   6.466x
 8   | 1.87e-08  2.68e-09   6.978x
 9   | 2.09e-08  2.54e-09   8.228x
10   | 2.41e-08  2.75e-09   8.764x
11   | 1.32e-08  2.64e-09   5.000x
12   | 1.35e-08  2.71e-09   4.982x
13   | 1.43e-08  2.73e-09   5.238x
14   | 1.53e-08  2.76e-09   5.543x
15   | 1.52e-08  2.82e-09   5.390x
16   | 7.01e-08  5.22e-09  13.429x
17   | 8.22e-08  5.39e-09  15.250x
18   | 9.50e-08  5.59e-09  16.995x
19   | 1.08e-07  5.76e-09  18.750x
20   | 1.21e-07  5.95e-09  20.336x
21   | 1.35e-07  1.35e-07   1.000x
22   | 1.47e-07  1.47e-07   1.000x

Timings generating the primes up to 10^3 sequentially using repeated calls to n_nextprime:

old:   1.53e-06
new:   6.02e-07  (2.5x speedup)

Timings generating the primes up to 10^6:

old:   0.00827
new:   0.00057  (14.5x speedup)

For comparison, repeatedly calling n_primes_next takes 3.92e-07 seconds up to 10^3 (where it's just copying from the small primes table) and 0.00115 seconds up to 10^6 (where it's sieving). Obviously, n_primes_next would benefit significantly from using the same tables as n_is_prime and n_nextprime, but I'm not going to touch that function for now (it wants other optimizations too).

This PR also removes the obsolete n_is_oddprime_small and n_is_oddprime_binary functions and replaces the obsolete n_is_probabprime with a wrapper of n_is_prime.

@fredrik-johansson fredrik-johansson merged commit b0eeb04 into flintlib:main Jan 12, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant