How to find power of a number in python without using pow function
View Discussion Show Improve Article Save Article View Discussion Improve Article Save Article Method 1 (Using Nested Loops): We can calculate power by using repeated addition. For example to calculate 5^6. 1)
First 5 times add 5, we get 25. (5^2) C++
C
Java
Python
C#
PHP
Javascript
Output : 125
Method 2 (Using Recursion): Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the power b. C++
C
Java
Python3
C#
PHP
Javascript
Output : 125
Method 3 (Using bit masking) Approach: We can a^n (let’s say 3^5) as 3^4 * 3^0 * 3^1 = 3^5, so we can represent 5 as its binary i.e. 101 C++
C
Java
Python3
C#
Javascript
PHP
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem. How do you find power without pow function?Find out Power without Using POW Function in C. 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.. How do you find the power of a number in Python?How to find the power of a number in Python. import math. print(math. pow(4,2)) Run. Importing math module in Python.. def power(n,e): res=0. for i in range(e): res *= n. return res. print(pow(4,2)) Run. ... . def power(n, e): if e == 0: return 1. elif e == 1: return n. else: return (n*power(n, e-1)). What is the code for power in Python?Python Power: ** Operator
The Python ** operator is used to raise a number in Python to the power of an exponent. In other words, ** is the power operator in Python. Our program returns the following result: 25 .
How do you find the power of a number in a for loop in Python?Example 1: Calculate power of a number using a while loop
Using the while loop, we keep on multiplying the result by base until the exponent becomes zero. In this case, we multiply result by base 4 times in total, so result = 1 * 3 * 3 * 3 * 3 = 81 .
|