Java中的Primality测试

时间:2015-11-28 15:20:09

标签: java double type-conversion long-integer pow

所以我正在进行一些素性测试,使用费马测试,以及我调用Precise的方法,这对于大整数来说太长了,但它是一个坚实的参考点我的Fermat方法是对还是错。 实际上,这两种方法之间的唯一区别是,虽然Fermat会检查a^(p-1) % p == 1 % p随机a的素数方程(k),Precise会检查区间(2 <= a <= p-2)中所有 a的等式。

我的问题是,为了计算a^(p-1),我需要使用一个返回整数的函数(为了计算除p之后的余数),所以我猜Math.random()是不可能的。

我该怎么办?我应该使用另一种方法来计算以某种方式返回整数的幂,如果是这样,怎么做?有没有这样的方法?

Fermat代码:

public static boolean Fermat(int p, int k)
{
    int a, i, counter = 0;
    int[] used_a = new int[p-3];

    a = (int) (Math.random() * (p-1) + 2);
    for(i=0;i<k;i++){
        used_a[counter] = a;
        if(Math.pow(a, p-1) % p != 1 % p){
            return false;
        }
        while((contains(used_a, a)) && (counter < p-4)){ // contains(int[] array, int key) is just a method which tells us if key is in the array
            a = (int) (Math.random() * (p-1) + 2);
        }
    }
    return true;
}

Precise代码:

public static boolean Precise(int p)
{
    int a;

    for(a=2;a<=p-2;a++){
        if(Math.pow(a, p-1) % p != 1 % p){
            return false;
        } 
    }
    return true;
}

0 个答案:

没有答案