Question

I just tried to implement Fermat's little theorem in JavaScript. I tried it both ways, a^(p-1) mod p = 1 and a^p mod p = a mod p.

function fermat(a, p) {
  return (((a ^ (p - 1)) % p) === 1);
}

and

function fermat(a, p) {
  return ( ( a^p ) % p ) === ( a % p );
}

It doesn't work both ways, is there any way to fix that?

Was it helpful?

Solution

In Javascript ^ means XOR. For exponentiation you need Math.pow(x, y).

function fermat(a, p) {
  return Math.pow(a, p - 1) % p === 1;
}

OTHER TIPS

Instead of ^, you need to use Math.pow

In addition to the ^ vs. Math.pow() issue others have pointed out, the next hurdle you will likely face is the limited precision of the Javascript built-in numeric types. You will very quickly exceed the range of exactly representable Javascript numbers once the exponents start getting large, as they will be if you're wanting to use a routine like this as a primality test. You may want to look into a Javascript bignum library (for example, this one) that supports exponentiation and modulus for arbitrarily large integers.

In javascript, the carat (^) is the XOR operator. What you want to use is the Math.pow(x,y) function which is equivalent to x^y.

Here is my code (JavaScript) for checking whether a number is prime based on Fermat Little Theorem.

    function getRandomInt(min,max) { /* getting a random between given max and min values */
        min = Math.ceil(min);
        max = Math.ceil(max);
        return Math.floor(Math.random()*(max-min))+min;
    }

    function getGCD(a,b) { /* getting the greatest common divisor */
        var tmp;
        while (b !== 0) {
            tmp = b;
            b = a%b;
            a = tmp;
        }
        return a;
    }

    function getPower(a,b,p) { /* getting the a^b mod p */
        if (b == 1)
         return a%p;
        else {
         x = getPower(a,Math.floor(b/2),p);
         if (b%2 == 0) 
          return (x*x)%p;
         else return (((x*x)%p)*a)%p;
        }
    }

    function fermatTesting(Num) { //Checking Num by using Fermat's theorem
        var a = getRandomInt(2,Num-1);
        if (getGCD(a,Num) !== 1) {
            return "COMPOSITE";
        }
        else {
            if (getPower(a,Num-1,Num) !== 1) {
                return "COMPOSITE";
            }
            else {
                return "PRIME"; 
            }
        }
    }

    console.log(fermatTesting(57)); //Displays "COMPOSITE"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top