prime_fermat


prime_fermat, a MATLAB code which applies Fermat's primality test to an integer n, which always correctly identifies primes, but sometimes also accepts nonprimes. Nonetheless, the test is useful for weeding out most nonprimes. The accuracy of the test can be improved by running it for several bases.

The test is based on Fermat's little theorem. If n is prime, and a is any number not divisible by n, then

      a^(n-1) = 1 mod n.
To test whether n is prime, we can pick a random value a and see if the congruence holds. If it does not, then n is definitely not prime. If it holds, we are not sure. We can repeat the test for several values of a to improve our confidence.

Licensing:

The information on this web page is distributed under the MIT license.

Languages:

prime_fermat is available in a C++ version and a MATLAB version and an Octave version.

Related Data and Programs:

prime_fermat_test

is_prime, a MATLAB code which determines if a given integer n is prime, using various versions of the sieve of Eratosthenes.

prime, a MATLAB code which counts primes between 1 and N, intended as a starting point for the creation of a parallel version.

prime_factors, a MATLAB code which returns a list of the prime factors of an integer.

prime_pi, a MATLAB code which evaluates Pi(n), the number of primes less than or equal to an integer n.

prime_plot, a MATLAB code which displays a box plot of the prime and composite numbers.

Reference:

  1. Thomas Cormen, Charles Leiserson, Ronald Rivest, Clifford Stein,
    Introduction to Algorithms,
    Section 31.8: Primality testing,
    MIT Press; McGraw-Hill, 2001.

Source Code:


Last revised on 20 September 2024.