题解 | #2的N次方#
2的N次方
https://www.nowcoder.com/practice/e9a4919b8848451d9aff81e3cdd133b1
解题思路
- 题目要求计算
,其中
的范围是
到
- 由于结果会非常大,需要使用合适的数据类型来存储
- 可以使用递归或迭代的方式计算
- 需要注意的是,结果要以十进制形式输出
- 使用
long double
类型可以保证结果的精确性
代码
#include <iostream>
using namespace std;
long double x = 2;
long double power(int n) {
if(n == 1)
return x;
else
return x * power(n-1);
}
int main() {
int N;
cin >> N;
printf("%.0Lf\n", power(N));
return 0;
}
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
// 使用BigInteger处理大数
BigInteger result = BigInteger.valueOf(2).pow(N);
System.out.println(result);
}
}
def power(n):
return 2 ** n
N = int(input())
print(power(N))
算法及复杂度
- 算法:递归或直接计算
- 时间复杂度:
- 递归版本需要
次乘法运算
- 空间复杂度:
- 递归版本需要
层栈空间