Javatpoint Logo
Javatpoint Logo

Find out Power without Using POW Function in C

The function pow() is used to calculate the power of a given integer. Now in this article we will going to understand with a help of a program how to calculate the power of a integer without using the function pow() in C.

Using for loop for Determining the Power of Given Integer

Imagine you need to locate a ^ b. The easiest method is to multiply a by b times using a loop.

  • Let a ^ b be the input. The base is a, while the exponent is b.
  • Start with a power of 1.
  • Using a loop, execute the following instructions b times
  • power = power * a
  • The power system has the final solution, a ^ b.

Let's understand the above approach better with an example of a program in C:

Output:

Enter Base: 5
Enter Power: 3
5 ^ 3 = 125
..........................
Process executed in 3.22 seconds
Press any key to continue.

Explanation

The code above has an O (N) time complexity, where N is the exponent. O is the space complexity (1).

Using While loop:

Output:

enter the number and its exponential :
5
4
5 ^ 6 = 625 
..........................
Process executed in 0.11 seconds
Press any key to continue.  

Explanation

Long Long Int is twice as large as Long Int. The format specifier for long long int is percent lld.

Using Recursion to find the Power of Given Integer

Assume that a ^ b is the input. The power of 'a' will increase by one with each recursive call. To obtain a ^ b, we call the recursive function b twice.

  • Let Pow ( a, b ) be the recursive function used to calculate a ^ b.
  • Simply return 1 if b == 0; else, return Pow (a, b -1) * a.

Let's understand the above approach better with an example of a program in C:

Output:

Enter Base: 5
Enter Power: 4
5 ^ 4 = 625
..........................
Process executed in 1.22 seconds
Press any key to continue.

Explanation:

In the above example of a code in C, time complexity would be exponent N, O(N) & O(N) space complexity, internal stack.


Next TopicExponential() in C





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA