Java Integer Mod modularExp(long base, long exp, int modulus)

Here you can find the source of modularExp(long base, long exp, int modulus)

Description

Compute modular exponentiation in O(log exp).

License

Open Source License

Parameter

Parameter Description
base Base of exponentiation. Limited to MAX SIZE OF LONG.
exp Exponent of exponentiation. Limited to MAX SIZE OF LONG.
modulus Modulus of exponentiation. Limited to MAX SIZE OF INT.

Return

result of exponentation base^exp % modulus

Declaration

public static int modularExp(long base, long exp, int modulus) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from   w  w w. j  a  v a  2s. c om
     * Compute modular exponentiation in O(log exp).
     * 
     * @param base
     *          Base of exponentiation. Limited to MAX SIZE OF LONG.
     * @param exp
     *          Exponent of exponentiation. Limited to MAX SIZE OF LONG.
     * @param modulus
     *          Modulus of exponentiation. Limited to MAX SIZE OF INT.
     * @return result of exponentation base^exp % modulus
     */
    public static int modularExp(long base, long exp, int modulus) {
        base = base % modulus; // make sure we're not doing extra work

        int toRet = 1;
        long[] modExpResults = new long[(int) log2(exp + 1) + 1]; // mer[i] =
        // base^2^i
        // seed array
        modExpResults[0] = (base % modulus); // base^1; cast okay because mod
        // limits to less than int

        // fill out rest of array by continuously doubling
        for (int i = 1; i < modExpResults.length; i++) {
            modExpResults[i] = (modExpResults[i - 1] * modExpResults[i - 1]) % modulus;
        }

        // multiply appropriate factors together
        int counter = 0;
        while (exp > 0) {
            if ((exp & 1) == 1) {
                toRet = (int) ((toRet * modExpResults[counter]) % modulus);
                // cast is okay because modulus is int
            }
            ++counter;
            exp >>= 1;
        }

        return toRet;
    }

    /**
     * Approximation of log_2. Accuracy limited by floating point arithmetic.
     * 
     * @param in
     *          Number on which to compute log_2
     * @return Log_2 of input
     */
    public static double log2(double in) {
        return Math.log(in) / Math.log(2);
    }
}

Related

  1. modInverse(int a, int n)
  2. modInverse(int n, int mod)
  3. modMultiply(long a, long b, int m)
  4. modPos(int divisor, int dividend)
  5. modSubtract(long a, long b, int m)
  6. modularInverses(int p)
  7. modularInvert(int num, int modulus)
  8. modulateCircularIndex(int index, int seqLength)
  9. modulo(int a, int b)