Print Exponential of A Number in Java

Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we find exponential numbers, seems too easy right!. So let’s quickly find out how to Print Exponential Of A Number in Java.

With the help of this program, you will be able to find the root square of integers. Practicing these types of questions also helps to get an upper edge in Competitive Programming.

 

What’s The Approach?

 

  • Let us consider x to be the number & y to be the exponent.

 

  • Now recursively firstly we’ll check if y % 2 == 0if yes then we’ll return  power(x, y / 2) * power(x, y / 2)

 

  • If not, then we’ll simply multiply x with the function recursively twice while dividing the value of exponent by 2. i.e, x * power(x, y / 2) * power(x, y / 2);

 

Also Read: Print Cube Root of A Number in Java

 

Java Program To Print Exponential of A Number

 

Input:

 

x = 2, y = 3

 

Output:

 

8

 

// Java Program To Print Exponential of A Number

class TechDecodeTutorials {

    /* Function to calculate x raised to the power y */
    static int power(int x, int y)
    {
        if (y == 0)
            return 1;
        else if (y % 2 == 0)
            return power(x, y / 2) * power(x, y / 2);
        else
            return x * power(x, y / 2) * power(x, y / 2);
    }

    /* Program to test function power */
    public static void main(String[] args)
    {
        int x = 2;
        int y = 3;

        System.out.printf("%d", power(x, y));
    }
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *