In this article, we will learn how to write a C program to calculate the power of a number (xn). We may assume that x and n are small and overflow doesn't happen.
-768.png)
C Program To Calculate the Power of a Number
A simple solution to calculate the power would be to multiply x exactly n times. We can do that by using a simple for or while loop.
// C program for the above approach
#include <stdio.h>
// 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);
printf("%d", result);
return 0;
}
Output
8
Complexity Analysis
- Time Complexity: O(n), to iterate n times.
- Auxiliary Space: O(1)
Please visit the article Write the Program to Find pow(x,y) to know about more methods to calculate the power of a number.
Related Articles
- Write an iterative O(Log y) function for pow(x, y)
- Modular Exponentiation (Power in Modular Arithmetic)