Fast Exponention using Bit Manipulation | Function to return a ^ n ; Stores final answer ; Check if current LSB is set ; Right shift ; Driver Code
function powerOptimised ( a , n ) { let ans = 1 ; while ( n > 0 ) { let last_bit = ( n & 1 ) ; if ( last_bit > 0 ) { ans = ans * a ; } a = a * a ; n = n >> 1 ; } return ans ; } let a = 3 , n = 5 ; document . write ( powerOptimised ( a , n ) ) ;