Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fermat's little theorem in JS

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?

like image 264
fb55 Avatar asked Aug 03 '10 19:08

fb55


1 Answers

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

function fermat(a, p) {
  return Math.pow(a, p - 1) % p === 1;
}
like image 102
Mark Byers Avatar answered Sep 20 '22 21:09

Mark Byers