How to Implement a Power Function in Java - Coding Problems

Even though the Java library has a power function, Math.pow() to calculate the power of a given number in Java, it's a common programming exercise for Java programmer 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 double 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


2. Solution:

You can solve this problem by writing a function which just multiplies given number to itself by given number of times. For example, if power(x, y) you can return the value of x multiplied by itself y number of times. This can easily 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 functions easily 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:

This problem is very similar to another popular 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 bitwise operator because it was the power of two and 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 Implement a Power Function in Java - Coding Problems



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

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 out power function is working as expected and all the powers are correct. I haven't tested with edge cases e.g. power of zero and power of Integer.MAX_VALUE but if you want you can test 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, negative 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 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)
  • Write a Java Program to calculate Simple Interest? (answer)
  • Top 20 System Design Interview Questions (list)

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


No comments:

Post a Comment