
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Pow(x, n) in Python
Suppose we have two inputs x and n. x is a number in range -100.0 to 100.0, and n is a 32-bit signed integer. We have to find x to the power n without using library functions.
So if the given inputs are x = 12.1, n = -2, then output will be 0.00683
To solve this, we will follow these steps −
- power := |n| and res := 1.0
- while power is not 0
- if last bit of power is 1, then res := res * x
- x := x * x
- if n < 0
- return 1 / res
- return res
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def myPow(self, x, n): power = abs(n) res = 1.0 while power: if power & 1: res*=x x*=x power>>=1 if n<0: return 1/res return res ob1 = Solution() print(ob1.myPow(45, -2)) print(ob1.myPow(21, 3))
Input
45 -2 21 3
Output
0.0004938271604938272 9261.0
- Related Articles
- Write a program to calculate pow(x,n) in C++
- pow() function in C
- pow() function in PHP
- Super Pow in C++
- Write an iterative O(Log y) function for pow(x, y) in C++
- PHP pow() Function
- Is POW() better or POWER() in MySQL?
- pow() function for complex number in C++
- Which one is better POW() or POWER() in MySQL?
- Write a power (pow) function using C++
- Python Program to Generate a Dictionary that Contains Numbers (between 1 and n) in the Form (x,x*x).
- Simplify:\( \sqrt[lm]{\frac{x^{l}}{x^{m}}} \times \sqrt[m n]{\frac{x^{m}}{x^{n}}} \times \sqrt[n l]{\frac{x^{n}}{x^{l}}} \)
- Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n in C++
- Program to find sum of 1 + x/2! + x^2/3! +…+x^n/(n+1)! in C++
- Find x."\n

Advertisements