Opening scenario
Pow(x, n) (LC 50). Implement
pow(x, n)—xa float,na (possibly negative, possibly large) integer — without using the built-in power, and faster than multiplyingxby itselfntimes. Follow-ups you should expect: Count Primes (LC 204) — count primes strictly less thann; and "computegcd(a, b)" and "computex^n mod mfor hugen".
LC numbers identify LeetCode problems.
Compare computing x^8 with eight repeated factors to computing x^2, then x^4, then x^8. How much work can be reused? Here x^n denotes mathematical exponentiation; Python writes it as x ** n, since ^ means bitwise XOR.
Question progression
Q1 — Why is the loop result *= x n times not acceptable?
Question: The naive pow multiplies x into an accumulator n times. What is that costing, and what structure in n are you ignoring?
Reasoning: Naive pow is O(n)…
In the full tutorial
- Canonical Template
- Complexity
- Pattern Recognition Signals
- Practice Set
- Pitfalls
- Variations
- Closing: When to Reach for This