Breaking
Coding Interview

# coding interview questions part 2

## Power

Power involves two numbers with a base a and the exponent n. Example 3 pow 4 = 3 x 3 x 3 x 3 = 81.
When n is a positive integer, exponentiation corresponds to repeated multiplication of the base. The languages have a built-in function to calculate the power.
Example:-
Power of 3 ^ 2 = (3 * 3) = 9.0

## Source Code

```package com.dsacode.Probelms;

public class Power {

private static double power(double x, int n) {
if (n == 0)
return 1;

double v = power(x, n / 2);

if (n % 2 == 0) {
return v * v;
} else {
return v * v * x;
}
}

public static double pow(double x, int n) {
if (n < 0) {
return 1 / power(x, -n);
} else {
return power(x, n);
}
}

public static void main(String[] args) {

System.out.println("Power of 3^2: " + pow(3,2));
System.out.println("Power of 3^2: " + Math.pow(3, 2));
}

}```
```#include "stdafx.h"

#include < iostream >
using namespace std;

unsigned int pwr(unsigned int base, unsigned int exp)
{
unsigned int result = 1;

while (exp--)
result *= base;

return result;
}

int _tmain(int argc, _TCHAR* argv[])
{
cout << "Power of 3^2: " << pwr(3, 4) << endl;
cout <<  "Power of 3^2: " << pwr(3, 2) << endl;

return 0;
}

```

## Output

`Power of 3^2: 9.0`

1 2 3 4 5