src/com/michaelho/RandomizedAlgorithms/RA2.java
/**
         * Determine if the number is a prime number using Fermat's method.
         * Reference: https://www.geeksforgeeks.org/primality-test-set-2-fermet-method/
         *
         * @param n The number to be determined.
         * @param k Try k times.
         * */
Determine if the number is a prime number using Fermat's method.

@param n The number to be determined.
@param k Try k times.
Determine if the number is a prime number using Fermat ' s method . @param n The number to be determined . @param k Try k times .
boolean isPrimeUsingFermat(int n, int k) {
            if (n <= 1 || n == 4) return false;
            if (n <= 3) return true;
            RA1 ra1 = new RA1();
            while (k > 0) {
                int x = 2 + (int)(Math.random() % (n - 4));
                if (ra1.ma.modularExp(x, n - 1, n) != 1)
                    return false;
                k--;
            }
            return true;
        }
boolean isPrimeUsingFermat ( int n , int k ) { if ( n <= 1 || n == 4 ) return false ; if ( n <= 3 ) return true ; RA1 ra1 = new RA1 ( ) ; while ( k > 0 ) { int x = 2 + ( int ) ( Math . random ( ) % ( n - 4 ) ) ; if ( ra1 . ma . modularExp ( x , n - 1 , n ) != 1 ) return false ; k -- ; } return true ; }
Determine if the number is a prime number using Fermat's method.
Determine if the number is a prime number using Fermat ' s method .
// Handle edge cases where n = 1, 2, 3, 4 // Try k times // Pick a random number in [2..n-2] // Fermat's little theorem