Saturday, September 16, 2023

How to Implement a Power Function in Java? Example Tutorial [Solved]

If you are preparing for a coding interview and wondering how to implement a function to calculate the power of x to y then you have come to the right place. Earlier, I have shared the best books, websites, and courses for coding interviews and in this article, I will show you how to solve this common coding problem from interviews with companies like Amazon, Flipkart, Google, and startups, and in this article  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 an integer, but beware that the power function may overflow.


How to write a function to calculate the power of integers

Write a function in Java to calculate the power of integers. In other words, write a program to find the value of a number raised to the power of another number in Java. 

Method Signature: power(int x, int y)

Purpose: Function should return the power of x^y

Input: power(2, 3) should return 8

Here is another definition of the Power function from Math's perspective just in case if you're interested. If you are preparing for a coding interview, I also suggest you revise essential data structure concepts together with simple Maths concepts. 

If you need a resource, I recommend Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It's both affordable and comprehensive enough to cover all essential data structures for interviews. 

How to Implement a Power Function in Java - Coding Problems


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 the 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 problem, the power of two, which we discussed earlier. In that problem, I have shown you two ways, one using multiplication and the 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 things 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 the 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.


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)
  • 7 Best Courses to learn Data Structure and Algorithms (best courses)
  • How to check if a number is an Armstrong number or not? (solution)
  • 10 Free Courses to learn Data STructure for beginners (free courses)
  • How to check if a number is even or odd in Java? (solution)
  • Top 5 Website to learn Python coding for FREE (websites)
  • 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 them 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 these free data structure courses on Udemy. It's authored by an ex-Google Programmer and Algorithm expert, and it's completely free of cost.

Now, its time for  question for you, can you find any issue with the code above? what is the limit of this function to calculate power? from which number it will start giving wrong answer and how do you solve it?

13 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
  2. Replies
    1. It doesn't handle that case now, but you can change the code to handle it easily.

      Delete
  3. Replies
    1. No, it doesn't handle decimal numbers, you can see that loop is incrementing by 1 so its only work for integer inputs. The argument of power is also int

      Delete
  4. Can you help me, i already figured out to make this kind of program that gets an input from the user the problem is. They want me to also display how the result is processed. For example, 2^4 is 16 but they want to display 2x2=4, 2x2x2=8, 2x2x2x2=16 something like that

    ReplyDelete
  5. please send me the updated answer , this program doesnt calculate x^0 ???

    ReplyDelete
  6. // will this work?
    public static long power(int x, int y) {
    long result = 1;

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

    return result;
    }

    ReplyDelete
    Replies
    1. I think, yes it will work, but better just test for power(2, 0) power(2,1) and power(2,10)

      Delete
    2. Tests
      power(2, 0) returns 1
      power(2, 1) returns 2
      power(2, 10) returns 1024

      Delete
  7. Hey there! I believe these codes won't work with negative numbers, can you by any chance write the codes for calculating the power of negative numbers? Like 2^-3 or -3^4, etc. I did manage to write them recursively, but I failed miserably with the iterative approach. Thanks! :)

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.