Knowledge Dump

fermat_test (C++17)

This function applies the Fermat primality test on an integer, with a customizable amount of runs. The Fermat Test is based on Fermat's little theorem, which states that if $p$ is prime and $a$ is an integer, the following statement holds true: $$a^p\equiv a\mod p.$$ If $a$ is not divisible by $p$, this is equivalent to $$a^{p-1}\equiv 1\mod p.$$ By reversing this statement, it follows that if $$a^{p-1}\not\equiv 1~\mod p$$ holds, $p$ can't be prime. By repeatedly checking this statement for different values of $a$, with $a\in[2,p-2]$, one can determine, whether $p$ is "likely prime" or not.
It should be noted that there exist numbers $n$, with $a^{n-1}\equiv 1\mod n$ for all $a<n$ with $\gcd(a,n)=1$. These numbers are called Carmichael numbers and they can only potentially be detected as non-prime by integers $a$ with $\gcd(a,n)\not=1$.

The implementation here uses the fundamental long long data type and a modular exponentiation function. Thus, it only works for numbers up to $\sqrt{2^{63}-1}\approx 3\cdot 10^9$. To avoid this restriction, a data type of unrestricted size could be used. Download(zip).