Here you can find the source of modularExp(long base, long exp, int modulus)
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. |
public static int modularExp(long base, long exp, int modulus)
//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); } }