真的没骗你,这道才是简单题 —— 对任意给定的不超过 10 的正整数 n,要求你输出 2
n
。不难吧?
输入格式:
输入在一行中给出一个不超过 10 的正整数 n。
输出格式:
在一行中按照格式 2^n = 计算结果 输出 2
n
的值。
输入样例:
5
输出样例:
2^5 = 32
优化一下用快速幂
#include<iostream>
#include<algorithm>
#include<vector>
#include<math.h>
using namespace std;
int quickpow(int a, int n)
{
int base = a;
int res = 1;
while (n)
{
if (n & 1)
res *= base;
base *= base;
n >>= 1;
}
return res;
}
int main()
{
int n;
cin >> n;
cout << "2^" << n << " = " << quickpow(2, n) << endl;
return 0;
}
本文介绍了一种高效计算指数运算的方法——快速幂算法。通过实例演示了如何使用快速幂算法计算2的n次方,其中n为不超过10的正整数。文章提供了详细的C++代码实现,展示了算法的具体步骤。
461

被折叠的 条评论
为什么被折叠?



