Algorithm Atlas · worked example
See the algorithm, step by step
Square the base and consume exponent bits so only logarithmically many multiplications occur.
This call is starting. Local values appear as they are initialized.
Data & variables
Changed Source indexExample input
base=3 exp=13 mod=1000Follow the code. Data appears here when it enters scope.
Call stack · 1 frame
maincall 1
Rust source
Line 16fn mod_power(mut base: u64, mut exponent: u64, modulus: u64) -> u64 {
assert!(modulus > 0);
let mut result = 1 % modulus;
base %= modulus;
while exponent > 0 {
if exponent & 1 == 1 {
result = (result as u128 * base as u128 % modulus as u128) as u64;
}
base = (base as u128 * base as u128 % modulus as u128) as u64;
exponent >>= 1;
}
result
}
fn main() {
let result = mod_power(3, 13, 1000).to_string();
println!("{result}");
}
Try your own version
Compare the visible input `base=3 exp=13 mod=1000` with `base=5 exp=3 mod=13`. Predict why their results are `323` and `8`. Then change one legal value and explain whether the same invariant, it processes one binary exponent bit per iteration, still applies.
Open personal copy in Playground ↗Start with this exact source and input, change a value, then use Run or Debug locally. This replay stays attached to the original example.
Recordings use a native Rust target. Playground runs on wasm32-wasip1; target-sized types such as usize can have different limits.

Understand it
For 3^13 mod 1000, exponent bits select powers 3,3^4 and 3^8. Multiplication and squaring are reduced modulo 1000; the final result is 323. u128 intermediates prevent overflow of two u64 factors before reduction.
The worked program is a complete executable for this pattern. Its core function uses typed input so the state transitions remain visible. The challenge input contract is: Parse base, exp and a positive mod; return base^exp modulo mod, including exp=0, so mod=1 gives 0. The visible fixture is base=3 exp=13 mod=1000 and its example result is 323. The implementation and additional semantic fixtures were checked against an independent reference calculation. Those bounded tests establish these examples; they are not a proof for all inputs or a measurement on an iPhone.
Return a canonical String from solve: lowercase true/false for booleans; decimal integers without extra signs, leading zeros or whitespace; comma-separated sequence values and semicolon-separated groups. Whole-number medians have no decimal suffix; half medians use .5. Do not append a newline to the returned value. Preserve the explicitly named textual sentinels such as none or #. Input fixtures are bounded so the demonstrated arithmetic fits its named Rust types; satisfy the stated input preconditions before applying the algorithm.
String and character-grid fixtures use ASCII unless the lesson explicitly specifies Unicode scalar values.
A problem is a good match for Binary Exponentiation when it asks for large powers, modular arithmetic, repeated transforms. Here the concrete task is: Parse base, exp and a positive mod; return base^exp modulo mod, including exp=0, so mod=1 gives 0. The visible input base=3 exp=13 mod=1000 is an example, not a definition of the whole problem. Ask what operations the solution must support and what the input guarantees. Check number size, sign, and modulus assumptions before using a shortcut; not every inverse or division exists. The right choice follows from those guarantees, not from a familiar noun in the prompt.
The decisive invariant is: Square the base and consume exponent bits so only logarithmically many multiplications occur. Try to say why it applies to the task without quoting the implementation. Which fact becomes known after one update, and which possible answers remain? An arithmetic or bitwise transformation relies on an identity. Write that identity and the domain in which it holds. If that claim cannot be maintained on a legal input, the pattern is wrong or one of its preconditions is missing. A counterexample is more useful than a vague warning: change one property of the sample, trace the first two steps, and identify the exact claim that fails.
Compare costs before committing. The advertised bound is O(log exponent) time · O(1) space; identify the operation responsible for it and the extra memory it needs. Then compare a straightforward alternative: a direct scan, full sort, or repeated recomputation may be easier but can pay for the same work many times. Do not choose the more elaborate method just because it has a famous name. For the sample, predict 323 and explain which part of the state lets the method reach that result.
When the prompt is ambiguous, ask about input size, ordering, duplicates, and required output format. Test zero, one, powers of two, maximum input size, and overflow or underflow around intermediate products. Use explicit integer widths and checked arithmetic when input bounds require them. Distinguish bit positions from numeric values. The Rust sketch can show a useful primitive without proving that the whole task is solved; connect each primitive to the requested output. You should be able to name a fitting case, a near miss, and the assumption separating them before writing the first line.
The pattern
Square the base and consume exponent bits so only logarithmically many multiplications occur.
When to use it: large powers, modular arithmetic, repeated transforms
Complexity: O(log exponent) time · O(1) space
Input: base=3 exp=13 mod=1000
Read the code
fn mod_power(mut base: u64, mut exponent: u64, modulus: u64) -> u64 {
assert!(modulus > 0);
let mut result = 1 % modulus;
base %= modulus;
while exponent > 0 {
if exponent & 1 == 1 {
result = (result as u128 * base as u128 % modulus as u128) as u64;
}
base = (base as u128 * base as u128 % modulus as u128) as u64;
exponent >>= 1;
}
result
}
fn main() {
let result = mod_power(3, 13, 1000).to_string();
println!("{result}");
}
Complete std-only fast-power program for its typed teaching fixture. Parsing and output construction are separate from the core algorithm.
Try it
Compare the visible and independent fixtures. Explain the input assumption that makes this algorithm applicable, then identify a change that would invalidate it.
What success looks like: You can justify the choice from constraints rather than from a remembered problem title.
Check your understanding
Trace Binary Exponentiation on input base=7 exp=0 mod=11. Which result follows from the documented contract?
Reveal the answer
210
For this input the result is 1. It processes one binary exponent bit per iteration. Compare this independent fixture with the worked trace: For 3^13 mod 1000, exponent bits select powers 3,3^4 and 3^8. Multiplication and squaring are reduced modulo 1000; the final result is 323. u128 intermediates prevent overflow of two u64 factors before reduction.
Go deeper
Common misconception: “It changes the desired exponent into a square root”
It processes one binary exponent bit per iteration. For 3^13 mod 1000, exponent bits select powers 3,3^4 and 3^8. Multiplication and squaring are reduced modulo 1000; the final result is 323. u128 intermediates prevent overflow of two u64 factors before reduction.
- Concrete transition: For 3^13 mod 1000, exponent bits select powers 3,3^4 and 3^8. Multiplication and squaring are reduced modulo 1000; the final result is 323. u128 intermediates prevent overflow of two u64 factors before reduction.
- Independent second fixture: Input
base=7 exp=0 mod=11produces1. Execute the named function in the worked program with these typed arguments, then compare its actual result with this independently computed expectation. - Boundary and contract: Input
base=2 exp=10 mod=17produces4. It processes one binary exponent bit per iteration. The stated work bound is O(log exponent) time · O(1) space. Count actual state changes; a successful output test alone does not prove that bound.
Transfer challenge: Compare the visible input base=3 exp=13 mod=1000 with base=5 exp=3 mod=13. Predict why their results are 323 and 8. Then change one legal value and explain whether the same invariant, it processes one binary exponent bit per iteration, still applies.
Connections
- Binary Exponentiation: Mental Model: Square the base and consume exponent bits so only logarithmically many multiplications occur.
- Challenge: Binary Exponentiation: Parse base, exp and a positive mod; return base^exp modulo mod, including exp=0, so mod=1 gives 0.
Reveal the Algorithm Atlas answer
323
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Binary Exponentiation: When to Use It (courseId "algorithms", lessonId "algorithm.fast-power.recognize") Link: https://crabrix.com/learn/algorithms/algorithm.fast-power.recognize Goal: It processes one binary exponent bit per iteration. State the input preconditions before applying this invariant. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=algorithms/algorithm.fast-power.recognize) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.