给定两个整数A和N,任务是计算提高到功率N(即A N)。
例子:
Input: A = 3, N = 5
Output: 243
Explanation:
3 raised to power 5 = (3*3*3*3*3) = 243
Input: A = 21, N = 4
Output: 194481
Explanation:
21 raised to power 4 = (21*21*21*21) = 194481
天真的方法:
解决此问题的最简单方法是反复将A , N乘以N ,然后打印出产品。
时间复杂度: O(N)
辅助空间: O(1)
高效方法:
为了优化上述方法,我们的想法是使用位操作。将整数N转换为其二进制形式,然后执行以下步骤:
- 初始化ans来存储A N的最终答案。
- 遍历直到N> 0,并在每次迭代中对其执行向右平移操作。
- 另外,在每次迭代中,将A与其自身相乘并对其进行更新。
- 如果设置了当前LSB,则将A的当前值乘以ans 。
- 最后,完成上述步骤后,打印ans 。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above appraoch
#include
using namespace std;
// Function to return a^n
int powerOptimised(int a, int n)
{
// Stores final answer
int ans = 1;
while (n > 0) {
int last_bit = (n & 1);
// Check if current LSB
// is set
if (last_bit) {
ans = ans * a;
}
a = a * a;
// Right shift
n = n >> 1;
}
return ans;
}
// Driver Code
int main()
{
int a = 3, n = 5;
cout << powerOptimised(a, n);
return 0;
}
Java
// Java program to implement
// the above appraoch
class GFG{
// Function to return a^n
static int powerOptimised(int a, int n)
{
// Stores final answer
int ans = 1;
while (n > 0)
{
int last_bit = (n & 1);
// Check if current LSB
// is set
if (last_bit > 0)
{
ans = ans * a;
}
a = a * a;
// Right shift
n = n >> 1;
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int a = 3, n = 5;
System.out.print(powerOptimised(a, n));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to implement
# the above approach
# Function to return a^n
def powerOptimised(a, n):
# Stores final answer
ans = 1
while (n > 0):
last_bit = (n & 1)
# Check if current LSB
# is set
if (last_bit):
ans = ans * a
a = a * a
# Right shift
n = n >> 1
return ans
# Driver code
if __name__ == '__main__':
a = 3
n = 5
print(powerOptimised(a,n))
# This code is contributed by virusbuddah_
C#
// C# program to implement
// the above appraoch
using System;
class GFG{
// Function to return a^n
static int powerOptimised(int a, int n)
{
// Stores readonly answer
int ans = 1;
while (n > 0)
{
int last_bit = (n & 1);
// Check if current LSB
// is set
if (last_bit > 0)
{
ans = ans * a;
}
a = a * a;
// Right shift
n = n >> 1;
}
return ans;
}
// Driver Code
public static void Main(String[] args)
{
int a = 3, n = 5;
Console.Write(powerOptimised(a, n));
}
}
// This code is contributed by Princi Singh
输出:
243
时间复杂度: O(logN)
辅助空间: O(1)