AlgoTales · Roadmap

Powers

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A power means multiplying a number by itself many times, such as 2 times 2 times 2. Things that double or repeat grow shockingly fast, and computing large powers cleverly, by pairing multiplications, keeps even huge calculations quick and safe.

Practical use cases

  • Web app: Compound interest in a loan calculator. A banking page shows the balance after 30 years of monthly interest. Multiplying by the rate 360 times works, but understanding it as a power lets you compute the result in one step and also explain why money grows faster and faster. The calculator becomes simple and its chart curves upward as users expect.
  • Web app: Password and PIN strength meters. A sign-up form says a password with 8 lowercase letters has 26 to the power 8 possibilities, and adding digits and capitals raises the base. Understanding powers shows why one extra character helps far more than one extra symbol type. The meter then gives honest advice.
  • System: Encryption and the repeated-squaring trick. HTTPS needs enormous powers with a remainder, far bigger than a computer could multiply one by one. A trick squares the number again and again, halving the work each time, so even a huge exponent takes only a few thousand steps.

The story: The Forwarded Joke

Kabir sent a funny cricket meme to two friends. Each friend forwarded it to two other friends, and those friends did the same. "By the tenth round, how many people will see it?" Mira asked. Kabir started drawing a family-tree of forwards, and ran out of paper after round four.

"Just multiply 2 by itself ten times," said Mrs. Sharma. "We write it as 2 to the power 10. Multiplying a number by itself again and again is called raising it to a power." Kabir did it on his fingers: 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024. "Over a thousand people, from one joke!"

"But what if I need 2 to the power 1000?" Kabir groaned. Mrs. Sharma showed him a trick: group the copies in pairs. 2 ten times is the same as (2×2) five times, which is 4 five times. Group again, and again. Instead of a thousand multiplications, you square the number only about ten times.

This square and halve trick (programmers call it fast exponentiation) turns a very long job into a tiny one. It will return in cryptography and in problems that ask for huge powers.

How to spot this problem, and where you need it

You need a number multiplied by itself many times, or you see something doubling again and again, and plain repeated multiplication is either too slow or overflows.

Signs you need it

  • The same factor is applied repeatedly: interest each month, doubling each round, or every added character multiplying the possibilities.
  • A loop that multiplies a million or a billion times is far too slow, or the result becomes too big to store.
  • A problem statement asks for a power with a huge exponent, often with the answer taken modulo a number.

Where to use it in a project

  • Interest, growth and depreciation calculators in finance, SaaS pricing and savings pages.
  • Security features that estimate password strength or work with cryptographic keys, hashes and checksums.

The solution

Do not multiply one at a time. If the exponent is even, square the base and halve the exponent. If it is odd, set aside one extra copy of the base and continue with an even exponent. Repeat until the exponent hits zero. Each step cuts the exponent in half, so a power of a billion needs only about thirty squarings. Keep remainders small along the way if the answer must stay within a limit.

Payoff: Before: a billion multiplications for one big power. After: about 30 squarings, finishing instantly.

Explain it like I am 8

A power just means "multiply the same number again and again". 2 to the power 3 is 2 × 2 × 2 = 8. The fast trick is to team up the numbers in pairs, so instead of lining up a hundred twos you only build a few bigger teams.

How it works, step by step

  1. Read the notation: "x to the power e" means x multiplied by itself e times; anything to the power 0 is 1.
  2. Start with answer = 1, a base x and the count e.
  3. If e is odd, move one copy of x into the answer: answer = answer * x.
  4. Square the base (x = x * x) and halve e, because pairs of copies are now single copies.
  5. Repeat until e is 0. The answer is complete, after only about log e rounds.

The code in four languages

PHP

<?php
// Slow way: multiply e times.
function slowPow(int $x, int $e): int {
    $answer = 1;
    for ($i = 0; $i < $e; $i++) $answer *= $x;
    return $answer;
}

// Fast way: square the base, halve the exponent.
function fastPow(int $x, int $e): int {
    $answer = 1;
    while ($e > 0) {
        if ($e % 2 === 1) $answer *= $x;   // odd: one copy left over
        $x *= $x;                          // pair the copies up
        $e = intdiv($e, 2);                // so there are half as many
    }
    return $answer;
}

echo slowPow(2, 10) . "
";    // 1024
echo fastPow(2, 10) . "
";    // 1024
echo fastPow(3, 13) . "
";    // 1594323
echo fastPow(7, 0) . "
";     // 1 (anything to the power 0)

JavaScript

// Slow way: multiply e times.
function slowPow(x, e) {
  let answer = 1;
  for (let i = 0; i < e; i++) answer *= x;
  return answer;
}

// Fast way: square the base, halve the exponent.
function fastPow(x, e) {
  let answer = 1;
  while (e > 0) {
    if (e % 2 === 1) answer *= x;    // odd: one copy left over
    x *= x;                          // pair the copies up
    e = Math.floor(e / 2);           // so there are half as many
  }
  return answer;
}

console.log(slowPow(2, 10));    // 1024
console.log(fastPow(2, 10));    // 1024
console.log(fastPow(3, 13));    // 1594323
console.log(fastPow(7, 0));     // 1 (anything to the power 0)

Java

public class Main {
    // Slow way: multiply e times.
    static long slowPow(long x, int e) {
        long answer = 1;
        for (int i = 0; i < e; i++) answer *= x;
        return answer;
    }

    // Fast way: square the base, halve the exponent.
    static long fastPow(long x, int e) {
        long answer = 1;
        while (e > 0) {
            if (e % 2 == 1) answer *= x;   // odd: one copy left over
            x *= x;                        // pair the copies up
            e = e / 2;                     // so there are half as many
        }
        return answer;
    }

    public static void main(String[] args) {
        System.out.println(slowPow(2, 10));    // 1024
        System.out.println(fastPow(2, 10));    // 1024
        System.out.println(fastPow(3, 13));    // 1594323
        System.out.println(fastPow(7, 0));     // 1 (anything to the power 0)
    }
}

Go

package main

import "fmt"

// slowPow: multiply e times.
func slowPow(x, e int) int {
	answer := 1
	for i := 0; i < e; i++ {
		answer *= x
	}
	return answer
}

// fastPow: square the base, halve the exponent.
func fastPow(x, e int) int {
	answer := 1
	for e > 0 {
		if e%2 == 1 {
			answer *= x // odd: one copy left over
		}
		x *= x // pair the copies up
		e /= 2 // so there are half as many
	}
	return answer
}

func main() {
	fmt.Println(slowPow(2, 10)) // 1024
	fmt.Println(fastPow(2, 10)) // 1024
	fmt.Println(fastPow(3, 13)) // 1594323
	fmt.Println(fastPow(7, 0))  // 1 (anything to the power 0)
}

Time: O(log e) for fast power (O(e) for the slow way) · Extra space: O(1). Each round halves the exponent, so a power of a billion needs only about 30 rounds.

Watch out for

  • Forgetting that anything to the power 0 is 1, so answer must start at 1, not 0.
  • Overflow: powers grow enormously fast, and a normal integer silently overflows (in JS, beyond about 9 quadrillion it loses precision).
  • Confusing 2 to the power 3 (= 8) with 2 × 3 (= 6).

Quick check

  1. What is 2 to the power 5?
    • 10
    • 32
    • 25
  2. In fast power, what do we do when e is odd?
    • Stop
    • Multiply the answer by the current x
    • Add 1 to x
  3. How many rounds does fast power need for e = 1000?
    • About 10
    • About 1000
    • About 500