Skip to content

Latest commit

 

History

History

Fast Exponentiation

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

Fast Exponentiation

Fast exponentiation is used for computing xn or x to the power n.

A naive approach would compute the following:

xn = (x • x • ... • x) n times

The overall time complexity is O(n).

We will use the method of exponentiation by squaring for fast computation. It is derived by observing the following to compute xn:

  • (xn/2)2 if n is even
  • x • (xn/2)2 if n is odd

where n/2 is the floor division.

In essence, we have reduced our problem size by half from size n to size n/2. Using this approach, we will have at most log n steps.

Time Complexity

Best Case: Ω(log n)

Average Case: θ(log n)

Worst Case: O(log n)

where n represents the power to be computed.

Space Complexity

Worst Case: O(1)

Function Description

Computes xn. The function power has the following parameters:

  • x: a double
  • n: an integer representing the power to be computed

Return value: a double which is the result of xn.

Input Format

A single line containing two space-separated values, the first being a double value representing x and the second being an integer value representing n.

Output Format

A single double value with 6 degrees of precision which is the result of xn.

Sample Input 0

10 0

Sample Output 0

1.000000

Sample Input 1

2 3

Sample Output 1

8.000000

Sample Input 2

2 -3

Sample Output 2

0.125000