题目
求n的m次方,n,m均为自然数。
实现
#include <iostream>
using namespace std;
int pow(int N){
int ans, n;
ans = 1;
n = 2;
while (N != 0){
if (N & 1 == 1){
ans = ans * n;
}
n = n * n;
N >>= 1;
}
return ans;
}
int main()
{
int x;
while(1){
cout<<endl;
cin>>x;
cout<<pow(x);
cout<<endl;
}
return 0;
}
解析
比如2^56可以分解成2^28*2^28,2^28可以分解为2^14*2^14,通过一层一层分解可以极大简化计算过程,思路是这样的,接下来是获得N次方的分解 我们通过>>= 二进制移位可以轻松获得,接着乘上即可