Skip to content

Commit

Permalink
write function for fast exponentiation in cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
justanindieguy committed Jan 31, 2023
1 parent 3e278db commit c71a212
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Bit-manipulationTechniques/FastExponentiation/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <iostream>

using namespace std;

int fastExponentiation(int a, int n)
{
int ans = 1;

while (n > 0)
{
int lastBit = n & 1;

if (lastBit)
ans *= a;

a *= a;
n = n >> 1;
}

return ans;
}

int main()
{
int a, n;
cin >> a >> n;

cout << fastExponentiation(a, n) << endl;

return 0;
}

0 comments on commit c71a212

Please sign in to comment.