📜  使用位操作的快速指数

📅  最后修改于: 2021-04-27 19:57:34             🧑  作者: Mango

给定两个整数AN,任务是计算提高到功率N(A N)。
例子:

天真的方法:
解决此问题的最简单方法是反复将AN乘以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)