Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Basic recursion

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Basic recursion

Pow(x, n) — Fast Exponentiation

intermediatelayer B10 · Basic recursion5 tests

Compute x raised to the power n without using Math.pow or the ** operator.

  • n is an integer and may be negative: x^-n is 1 / x^n
  • n = 0 gives 1 for any x
  • Multiplying n times is O(n) and far too slow for large exponents. Use fast exponentiation: squaring the base halves the exponent each step, giving O(log n)
  • Watch the most negative 32-bit exponent, -2147483648 — negating it must not break your loop

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen