Created
November 22, 2024 04:41
-
-
Save uhop/e9d8aa6acb68ae017d22589cc620bfe4 to your computer and use it in GitHub Desktop.
Fast pow() vs. slow pow()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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