Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a program to calculate pow(x,n) in C++
In this problem, we are given two integers x and n. Our task is to write a program to calculate the pow(x,n).
Let's take an example to understand the problem,
<b>Input:</b> x = 5 , n = 3 <b>Output:</b> 125
Example
Program to calculate the pow(x,n):
#include <iostream>
using namespace std;
float myPow(float x, int y) {
if (y == 0)
return 1;
float temp = myPow(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else {
if (y > 0)
return x * temp * temp;
else
return (temp * temp) / x;
}
}
int main() {
float x = 5;
int n = 7;
cout << "Raised to the power " << n << " is " << myPow(x, n);
return 0;
}
Output
Raised to the power 7 is 78125
The program shows an efficient approach by dividing the power into half and then multiplying the two half and also considers the negative cases.
Advertisements
