高精度乘法求2的N次方幂
#include <bits/stdc++.h>
using namespace std;
#define N 3010
int main()
{
int a[N]={1};
int i,t=0;
int n,m=1;
cin>>n;
for(i=0;i<n;i++)
{
t=0;
for(int j=0;j<m;j++)
{
int x=a[j];
a[j]=(a[j]*2+t)%10;
t=(x*2+t)/10;
}
//进位
if(t)a[m++]=1;
}
for(i=m-1;i>=0;i--)
{
cout<<a[i];
}
return 0;
}
快速幂+位运算求2的n次方幂(最快方法)
#include <bits/stdc++.h>
using namespace std;
// 直接利用位运算计算2的n次方
long long quick_pow(unsigned int n) {
// 1ULL 是无符号长长整型字面量,确保结果也是无符号长长整型
//位左移操作符<<将1左移n位,这相当于乘以2的n次方。
return (n == 0) ? 1 : (1ULL << n);
}
int main() {
//加快输入输出的速度,提高程序的执行效率
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
unsigned int n;
cout << "请输入n的值: ";
cin >> n;
unsigned long long result = quick_pow(n);
cout << "2的" << n << "次方是: " << result << endl;
return 0;
}