views:

59

answers:

3

I am trying to implement either the Fermat, Miller-Rabin, or AKS algorithm in Java using the BigInteger class.

I think I have the Fermat test implemented except that the BigInteger class doesn't allow taking BigIntegers to the power of BigIntegers (one can only take BigIntegers to the power of primitive ints). Is there a way around this?

The problematic line is denoted in my code:

public static boolean fermatPrimalityTest(BigInteger n)
{
    BigInteger a;
    Random rand = new Random();
    int maxIterations = 100000;

    for (int i = 0; i < maxIterations; i++) {
        a = new BigInteger(2048, rand);

        // PROBLEM WITH a.pow(n) BECAUSE n IS NOT A BigInteger
        boolean test = ((a.pow(n)).minus(BigInteger.ONE)).equals((BigInteger.ONE).mod(n));

        if (!test)
            return false;
    }

    return true;
}

Thanks for any direction!

+3  A: 

I think BigInteger.modPow might be what you're looking for. Note the "mod m" in Fermat's test.

Alan Krueger
I was looking at modPow; however, I'm not sure how to change "a^(n-1) = 1 mod n" to use modPow. I'm not too familiar with modular arithmetic.
DT3
`base.modPow(exponent, modulus)`, so in your case `a.modPow(n-1, n)`
Alan Krueger
Also note that a.pow(n), in general, can be quite ridiculously large. You might not have enough disk space to hold that number in binary! Doing something more sophisticated, such as modPow, is truly necessary.
Josephine
A: 

You'll have to implement your own pow() method. Look at the sources of BigInteger.pow() as a starting point.

Eugene Kuleshov
For very large integers that will be unnecessarily expensive, particularly when the algorithm only cares about the power over a particular modulus.
Alan Krueger
+1  A: 

One of the primality tests is built into BigInteger.isProbablePrime(). Not sure which one, you'd have to look at the source.

Also, you can raise a number to a power by multiplying. For example: 2^100 = 2^50 * 2^50. So pull out pieces of your BigInteger power and loop until you've used it up. But are you sure you don't mean to use BigInteger.modPow(), which takes BigIntegers? It looks like you are, based on your test.

Jonathan
I would like to build my own primality test rather than using a pre-existing one. I was looking at modPow; however, I'm not sure how to change "a^(n-1) = 1 mod n" to use modPow. I'm not too familiar with modular arithmetic.
DT3
If, for instance, it was a homework assignment, using a built-in test wouldn't cut it. Hypothetically speaking, of course.
Alan Krueger
It wasn't tagged with `homework`...
Jonathan
Ducks generally do not need a label saying "duck" on them to be identified as such.
Alan Krueger