O(1) runtime prime checking

Revision en1, by tweety, 2020-07-10 08:15:17

Hello fellow people of Codeforces

I hope everyone doing well in these uncertain and unprecedented times. I wanted to share this cool C++20 trick that I learned recently.

Check out this cool implementation of is_prime(n) to test if n integer is prime in O(1) runtime

bool is_prime(int n);

This code computes primes up to MAXN during compilation and stores them in a table right in the compiled binary. On a runtime is_prime(n) call, it queries the compiled table to find the result. Check this compiled assembly on the left side of the screen to find the sieve mask baked in the binary: https://godbolt.org/z/G6o84x.

This trick is achieved by passing the constructed Sieve as a template argument, which is always evaluated on compile-time. If you compile this code using older C++ standard, you will get the error:

error: a non-type template parameter cannot have type 'Sieve<MAXN>'

However, since C++20, non-type template parameter can have any LiteralType (note). In short, it is possible to compile-time compute an instance of any class with a constexpr constructor.

Here is a time test of compile-time vs run-time sieve computation:

main.cpp

Compiled with GCC 9.3.0 using the command g++ -std=c++2a main.cpp. This is the execution output on my laptop:

Runtime ans: 90. Elapsed (ms): 1008
Compiletime ans: 90. Elapsed (ms): 0

Of course no one re-computes sieve 1000 times, this is done here for the sole purpose of showing that the algorithm is not computing sieve in run time 1000 times.

While such tricks won't help you cheat pass Codeforces problems, they might will help your submission stand out for fastest runtimes. Hope you found this interesting!

Tags c++, c++20, imissyoucodeforces

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English tweety 2020-07-10 08:23:30 31 Tiny change: ' assembly on the left side of the screen to find t' -> ' assembly to find t'
en2 English tweety 2020-07-10 08:15:59 40 Tiny change: '1) runtime\n\n<spoil' -> '1) runtime (without any runtime precomputation!)\n\n<spoil'
en1 English tweety 2020-07-10 08:15:17 4713 Initial revision (published)