← All examples

Fast exponentiation

Java Algorithms

binary exponentiation

Flowchart (ISO 5807)

YesYesNoNoStartInput base, expresult = 1exp > 0exp % 2 == 1result = result * basebase = base * baseexp = exp / 2Return resultEndFigure 1 — Power.fastPow

Source code

class Power {
    static long fastPow(long base, int exp) {
        long result = 1;
        while (exp > 0) {
            if (exp % 2 == 1) {
                result = result * base;
            }
            base = base * base;
            exp = exp / 2;
        }
        return result;
    }
}