Skip to content

Fast exponentiation

Java binary exponentiation

Flowchart (ISO 5807)

YesYesNoNoStartInput base, expresult = 1exp > 0exp mod 2 = 1result = result·basebase = base²exp = exp / 2Return resultEndFigure 1 — Power.fastPow

Source code

Java
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;
    }
}

The editor opens with this code — change it and the chart redraws.

Language
Java
Constructs
binary exponentiation
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples