Print Exponential of A Number in C++

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 C++.

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: Swap Three Integers Without Temporary Variable in C++

 

C++ Program To Print Exponential of A Number

 

Input:

 

x = 2, y = 3

 

Output:

 

8

 

// C++ program to Print Exponential of A Number

#include<iostream>
using namespace std;
class TechDecodeTutorials
{
    
/* Function to calculate x raised to the power y */
public:
int power(int x, unsigned 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);
}
};

/* Driver code */
int main()
{
    TechDecodeTutorials TDT;
    int x = 2;
    unsigned int y = 3;

    cout << TDT.power(x, y);
    return 0;
}

 

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 *