typelevel / algebra
 1 ```package algebra.instances ``` 2 3 ```import scala.annotation.tailrec ``` 4 5 ```object StaticMethods { ``` 6 7 ``` /** ``` 8 ``` * Exponentiation function, e.g. x^y ``` 9 ``` * ``` 10 ``` * If base^ex doesn't fit in a Long, the result will overflow (unlike ``` 11 ``` * Math.pow which will return +/- Infinity). ``` 12 ``` */ ``` 13 ``` final def pow(base: Long, exponent: Long): Long = { ``` 14 ``` @tailrec def loop(t: Long, b: Long, e: Long): Long = ``` 15 2 ``` if (e == 0L) t ``` 16 2 ``` else if ((e & 1) == 1) loop(t * b, b * b, e >>> 1L) ``` 17 2 ``` else loop(t, b * b, e >>> 1L) ``` 18 19 2 ``` if (exponent >= 0L) loop(1L, base, exponent) else { ``` 20 0 ``` if(base == 0L) throw new ArithmeticException("zero can't be raised to negative power") ``` 21 0 ``` else if (base == 1L) 1L ``` 22 0 ``` else if (base == -1L) if ((exponent & 1L) == 0L) -1L else 1L ``` 23 0 ``` else 0L ``` 24 ``` } ``` 25 ``` } ``` 26 ```} ```

Read our documentation on viewing source code .