Created
April 4, 2020 03:58
-
-
Save edadma/a08cf3857b5094dd9ae1dfe9f49300f5 to your computer and use it in GitHub Desktop.
Tail recursive exponentiation by squaring
This file contains 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
def pow(x: Int, n: Int) = { | |
def pow(y: Int, x: Int, n: Int): Int = | |
n match { | |
case 0 => 1 | |
case 1 => x * y | |
case _ if n % 2 == 0 => pow(y, x * x, n / 2) | |
case _ => pow(x * y, x * x, (n - 1) / 2) | |
} | |
if (n < 0) sys.error(s"pow: negative exponent: $n") else pow(1, x, n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment