基本快速幂算法
1 #include<cstdio> 2 #include<cstdlib> 3 #include<iostream> 4 using namespace std; 5 int pow(int a, int b) 6 { 7 if(b == 0) 8 return 1; 9 else if(b == 1) 10 return a; 11 else 12 { 13 int c = pow(a, b / 2); 14 if((b % 2) == 0) 15 return c * c; 16 else 17 return c * c * a; 18 } 19 } 20 21 int main() 22 { 23 int x, n; 24 cin >> x >> n; 25 cout << pow(x, n) << endl; 26 return 0; 27 }
位优化快速幂算法
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 using namespace std; 5 6 long long Pow(long long x, long long n) 7 { 8 long long result; 9 if(n == 0) 10 return 1; 11 else 12 { 13 while((n & 1) == 0) 14 { 15 n >> 1; 16 x *= x; 17 } 18 } 19 result = x; 20 n >> 1; 21 while(n != 0) 22 { 23 x *= x; 24 if((n & 1) != 0) 25 result *= x; 26 n >> 1; 27 } 28 return result; 29 } 30 31 int main() 32 { 33 long long x, n; 34 cin >> x >> n; 35 cout << Pow(x, n) << endl; 36 return 0; 37 }