费马在JS中的小定理

时间:2010-08-03 19:56:07

标签: javascript algebra

我只是尝试在JavaScript中实现Fermat的小定理。我尝试了两种方式,一个^(p-1)mod p = 1和一个^ p mod p =一个mod p。

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

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

这两种方式都不起作用,有什么方法可以解决这个问题吗?

5 个答案:

答案 0 :(得分:9)

在Javascript中^表示XOR。对于exponentiation,您需要Math.pow(x, y)

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

答案 1 :(得分:7)

而不是^,您需要使用Math.pow

答案 2 :(得分:3)

除了^ vs. Math.pow()问题,其他人已经指出,下一个障碍 您可能面临的是Javascript内置数字的精度有限 类型。您将很快超出可准确表示的Javascript范围 一旦指数开始变大,就会出现数字,正如你想要的那样 使用像这样的例程作为素性测试。你可能想要研究一下 支持取幂的Javascript bignum库(例如,this one) 和任意大整数的模数。

答案 3 :(得分:2)

在javascript中,克拉(^)是XOR运算符。你想要使用的是Math.pow(x,y)函数,它相当于x ^ y。

答案 4 :(得分:0)

这是我的代码(JavaScript),用于根据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"