How to Implement a Power Function in Java - Coding Interview Question

Even though the Java library has a power function, Math.pow(), to calculate the power of a given number in Java, it's a regular programming exercise for Java programmers to implement a power function. If you have used the Math class, then you know that the java.lang.Math.pow(double a, double b) returns the value of the first number raised to the power of the second number and you need to do the same. In other words, you need to write a Java function to calculate the power of integer numbers for simplicity. The original method accepts a binary value, but you are allowed to use just integer, but beware that power function may overflow.

1. Problem:

Write a function in Java to calculate the power of integers.

Method Signature: power(int x, int y)

Purpose: Function should return the power of x^y

Input: power(2, 3) shouls return 8

Here is another definition of Power function from Maths perspective just in case if you re interested.

How to Implement a Power Function in Java - Coding Problems


2. Java Program to Calculate Power of X to Y:

You can solve this problem by writing a function that just multiplies a given number to itself by a given amount of times. For example, if power(x, y), you can return the value of x multiplied by itself y number of times. This can quickly be done in a loop, as shown in our Java program in the next section, but here is how the sample code looks like:

 public static long power(int x, int y) {
    long result = x;

    for (int i = 1; i < y; i++) {
      result = result * x;
    }

    return result;
  }

If you want, you can also start the loop from y and went down until you reach 1, but I like this approach. The function returns the power of x^y.

Even though you can write this kind of function quickly, it's far from ideal, and if you really need a power function for your production code, I suggest you use Math.pow() function because it's thoroughly tested.

This is also one of the lessons I learned from Joshua Bloch's class Effective Java book, which advice preferring library functions instead of writing your own.




3. Analysis and Explanation of Logic:

This problem is very similar to another famous coding problems, the power of two, which we discussed earlier. In that problem, I have shown you two ways, one using multiplication and other using a bitwise operator because it was the power of two, and the left shift is equal to multiplying by two.

Unfortunately, we cannot use the same technique here; hence, I have just shown the solution using the multiplication operator.

If you are not familiar with the bitwise operator and other essential Java operators, you can start with The Complete Java Masterclass to learn more about it.

How to calculate power of x to y in Java



4. Java Program to calculate the power of a number in Java

Here is our complete Java Program to calculate the power of x to y. In order to do that, we have created a Java method pow(x, y), which returns x to the power y.  This is a static method because code is not dependent upon any state. All the thing code needs to calculate power is coming via function parameters.  

package tool;

/**
 * 
 * A simple Java Program to implement a power function pow(x, y) which should
 * return x^y.
 * 
 * Input : (2, 3) Output: 8
 */
public class Hello {

  public static void main(String[] args) {

    System.out.println("2 to the power 3 : = " + power(2, 3));
    System.out.println("3 to the power 3 : = " + power(3, 3));
    System.out.println("2 to the power 5 : = " + power(2, 5));
    System.out.println("5 to the power 2 : = " + power(5, 2));
    System.out.println("9 to the power 2 : = " + power(9, 2));
  }

  /*
   * Calculate power using multiplication operator
   */
  public static long power(int x, int y) {
    long result = x;

    for (int i = 1; i < y; i++) {
      result = result * x;
    }

    return result;
  }

}

Output:
2 to the power 3 : = 8
3 to the power 3 : = 27
2 to the power 5 : = 32
5 to the power 2 : = 25
9 to the power 2 : = 81

You can see that our power function is working as expected, and all the powers are correct. I haven't tested with edge cases, like the power of zero and power of Integer.MAX_VALUE but if you want, you can check and fix any error.

In general, if illegal arguments are pass to the function, then you have the option to throw IllegalArgumentException to signal-caller that invalid values are supplied to the function.

That's all about how to calculate the power of a number in Java. You can see that our method is behaving as per expectation, but if you want, you can test more up to the mind when it really tests the logic, e.g., trying out invalid values like zero, contrary, etc. Also, trying with the maximum value of Integer and see if the program works fine or not.

Further Learning
The Complete Java Masterclass
Data Structures and Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language


Other Common Programming Problems to Learn Coding
  • Top 75 Programming Interview Questions (list)
  • How to check if a number is a palindrome or not? (solution)
  • How to check if a number is an Armstrong number or not? (solution)
  • How to check if a number is even or odd in Java? (solution)
  • Top 21 String Programming and Coding Questions from Interview (list)
  • Write a program to print the Fibonacci series in Java using recursion? (solution)
  • How to print Alphabets in upper and lower case in Java? (solution)
  • How to reverse a String in Java? (answer)
  • 10 Free Courses to learn Python Programming for Beginners (courses)
  • Write a Java Program to calculate Simple Interest? (answer)
  • Top 20 System Design Interview Questions (list)
  • 101 Coding Problems and some Tips for Interviews (questions)
  • 10 Courses to learn Data Structure and Algorithms (courses)

Thanks for reading this article so far. If you like these coding problems, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.


P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Easy to Advanced Data Structures course on Udemy. It's authored by an ex-Google Programmer and Algorithm expert, and it's completely free of cost.

2 comments:

  1. This function is incorrect. It evaluates x^0 to x, but should evaluate to 1.

    ReplyDelete
    Replies
    1. Ah yes, do you know how to fix that problem? just add a special case to return if(y==0) then return 1; Anyway, I'll update the article. Thanks for pointing it.

      Delete