Skip to content

Instantly share code, notes, and snippets.

@uhop
Created November 22, 2024 04:41
Show Gist options
  • Save uhop/e9d8aa6acb68ae017d22589cc620bfe4 to your computer and use it in GitHub Desktop.
Save uhop/e9d8aa6acb68ae017d22589cc620bfe4 to your computer and use it in GitHub Desktop.
Fast pow() vs. slow pow()
const fastPow = (x, n) => {
if (x <= 0) return 0;
if (n === 0) return 1;
if (n === 1) return x;
const result = fastPow(x, n >> 1);
return (n & 1) ? result * x : result;
};
const slowPow = (x, n) => {
if (x <= 0) return 0;
let result = 1;
for (let i = 0; i < n; ++i) {
result *= x;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment