Binary Exponentiation Algorithm
In mathematics and computer programming, exponentiating by squaring is a general method for fast calculation of large positive integer powers of a number, or more generally of an component of a semigroup, like a polynomial or a square matrix. For semigroups for which additive notation is normally used, like elliptic curves used in cryptanalysis, this method is also referred to as double-and-add.
package Mathematics
object BinaryExponentiation {
/**
* Method returns the binary exponentiation of a given number
when base and power are passed the parameters
*
* @param Int, Int
* @return
*/
def binaryExponentiation(base : Int, power : Int): Int = {
if (power == 0) {
return 1
} else if (power % 2 == 1) {
return binaryExponentiation(base, power - 1) * base
} else {
val answer : Int= binaryExponentiation(base, power / 2)
return answer * answer
}
}
}