Coding Interview

coding interview questions part 2

Pinterest LinkedIn Tumblr

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

Algorithm Explanation

Get the base and exponent numbers and validate the exponent number.
If exponent is negative, 1 / power(x, -n). Else calculate power(x, n);
Power calls recursively and returns the values based on exponent value
Pow returns the power of x, n
1 2 3 4 5

Write A Comment