Program to calculate pow(x, n) using Naive Approach
A simple solution to calculate pow(x, n) would multiply x exactly n times. We can do that by using a simple for loop
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Naive iterative solution to calculate pow(x, n) long power( int x, unsigned n) { // Initialize result to 1 long long pow = 1; // Multiply x for n times for ( int i = 0; i < n; i++) { pow = pow * x; } return pow ; } // Driver code int main( void ) { int x = 2; unsigned n = 3; // Function call int result = power(x, n); cout << result << endl; return 0; } |
Output
8
- Time Complexity: O(n)
- Auxiliary Space: O(1)
C++ Program To Calculate the Power of a Number
Write a C++ program for a given two integers x and n, write a function to compute xn. We may assume that x and n are small and overflow doesn’t happen.
Examples :
Input : x = 2, n = 3
Output : 8Input : x = 7, n = 2
Output : 49
Contact Us