Prompt the best algorithm for the realization of the construction of a power function (pow).

## Answer 1, Authority 100%

Maybe this is not the best way, but it works!

```
long int pow (long int x, unsigned int n)
{
if (n == 0)
return 1;
else if (n == 1)
return x;
else if (n% 2 == 0)
return pow (x * x, n / 2);
ELSE.
return pow (x * x, n / 2) * x;
}
```

## Answer 2, authority 80%

Specify the question, or the previous answer is correct. If it is necessary to calculate the degree of real numbers, the equation b ^ x = exp (x * ln (b)). If you want to implement and functions exponential and natural logarithm, please – unpack their by Taylor

.

## Answer 3, authority 80%

Note to all answers. What to do with the overflow? Nowhere it is not analyzed.

For example a library function

```
double pow (double x, double y)
```

sets errno to ERANGE

## Answer 4, authority 80%

**Shortest code (: **

```
class big {/ * implementation of long arithmetic * /};
big BinPow (big a, long long n) {
big res = big (1); // here res = 1
while (n) n & amp; 1 ? (Res * = a, --n): (a * = a, n & gt; & gt; 1);
reutn res;
}
```

In general, the properties are used here:

1. a ^ n = a ^ (n / 2) * a ^ (n / 2) – for odd n;

2. a ^ n = a ^ (n / 1) * a -. For even n

Dlinka for pathos (:

## Answer 5, authority 60%

I would implement the same algorithm as in the first answer, but iteratively, without spending too much time on the recursive call and O (log n) memory in the call stack, and with a few optimizations. The following code works only for non-negative integer n, for other values of n using a Taylor series expansion.

```
long int pow (long int x, unsigned int n)
{
long int a = x, p = 1;
while (n & gt; 0)
{
if ((n & amp;! 1) = 0)
p * = a;
a * = a;
n & gt; & gt; = 1;
}
return p;
}
```

## Answer 6, authority 20%

There is a lot simpler:

```
int pwr (register int m, register int e)
{
register int temp;
temp = 1;
for (; e; e--)
temps = temp * m;
return temp;
}
```

## Answer 7

```
int pow (int a, int n)
{
if (n == 0) return 1;
ELSE.
if (n == 1) return a;
ELSE.
return pow (a + a, n-1);
}
```